def main n = STDIN.readline.chomp.to_i queue = [{index: 1, count: 1}] visited = [] visited[1] = true while queue.size > 0 q = queue[0] if q[:index] == n puts q[:count] return end f = forward(q[:index]) if f <= n && visited[f].nil? queue << {index: f, count: q[:count] + 1} visited[f] = true end b = back(q[:index]) if b >= 1 && visited[b].nil? queue << {index: b, count: q[:count] + 1} visited[b] = true end queue.shift end end def forward(n) n + bit_count(n) end def back(n) n - bit_count(n) end def bit_count(n) count = 0 n.bit_length.times {|i| count += 1 if n[i] == 1} count end main()