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(n + 1, -1) dp[0] = 0 dp[1] = 1 candidates = [1] while !candidates.empty? candidate = candidates.shift break if candidate == n step = bit_count(candidate) if step < candidate && dp[candidate - step] < 0 dp[candidate - step] = dp[candidate] + 1 candidates << candidate - step end if step + candidate <= n && dp[candidate + step] < 0 dp[candidate + step] = dp[candidate] + 1 candidates << candidate + step end end dp[n] end puts main