# Here your code ! # via : http://www.nminoru.jp/~nminoru/programming/bitcount.html class Fixnum BITS_MATERIAL = [ 0x55555555, 0x33333333, 0x0f0f0f0f, 0x00ff00ff, 0x0000ffff ] def bits BITS_MATERIAL.each_with_index.inject(self) {|s,(v,i)| (s & v) + ((s >> 2**i) & v) } end end n = gets.to_i INF = 2000000 RANGE = (1..n) dp = Array.new(n+1, INF) q = [1] dp[1] = 1 g = -1 until q.empty? c = q.shift i = dp[c] if c == n g = i end d = c.bits [c + d, c - d].select { |v| RANGE.include?(v) }.each do |v| if i + 1 < dp[v] q.push(v) dp[v] = i + 1 end end end puts g