def bits(n) count = 0 while n > 0 count += n % 2 n /= 2 end count end n = gets.to_i queue = [[1, 1]] visited = Array.new(n + 1) loop do head = queue.shift if head.nil? puts -1 break end position, distance = head if position == n puts distance break end b = bits(position) [position + b, position - b].each do |p| queue << [p, distance + 1] unless p < 0 || p > n || visited[position] == 1 end visited[position] = 1 end