N = gets.to_i result = -1 queue = [{pos: 1, time: 1}] check = Array.new(N+1, false) check[1] = true while queue.length > 0 do current = queue.shift if current[:pos] == N result = current[:time] break end move = current[:pos].to_s(2).count("1") if current[:pos] - move > 0 && !check[current[:pos] - move] queue << {pos: current[:pos] - move, time: current[:time] + 1} check[current[:pos] - move] = true end if current[:pos] + move <= N && !check[current[:pos] + move] queue << {pos: current[:pos] + move, time: current[:time] + 1} check[current[:pos] + move] = true end end p result