def bit_count(n) cnt = 0 while 0 < n n &= n - 1 cnt += 1 end cnt end def main n = gets.to_i dp = Array.new(10001, 0) dp[0] = 1 queue = [1] while 0 < queue.length pos = queue.shift bc = bit_count(pos) [pos + bc, pos - bc].each do |next_pos| next if next_pos < 2 && 10000 < next_pos return dp[pos] + 1 if next_pos == n dp[next_pos] = dp[pos] + 1 queue << next_pos end end -1 end puts main