N = gets.to_i INF = 10000 @dp = Array.new(N+1, INF) @dp[1] = 1 def binary_1_count(num) count_1 = 0 while num > 1 do count_1 += 1 if num % 2 == 1 num /= 2 end count_1 += 1 end # iと書かれたマスに@dp(i)回目で移動してきた # @dpのこの位置は前もって書いてあるものとする def move(i) count = binary_1_count(i) if i - count > 0 && @dp[i]+1 < @dp[i-count] @dp[i-count] = @dp[i]+1 move(i-count) end if i + count <= N && @dp[i]+1 < @dp[i+count] @dp[i+count] = @dp[i]+1 move(i+count) end end move(1) if @dp[N] == INF puts -1 else puts @dp[N] end