def process(count, ni) if ni == $n $min = count if count < $min return end $b[ni] = true front = ni + $bit[ni] back = ni - $bit[ni] if front <= $n && !$b[front] process(count + 1, front) end if back > 0 && !$b[back] process(count + 1, back) end return end $n = gets.to_i $b = Array.new($n + 1, false) $bit = Array.new($n + 1, 0) $min = 99999999 ($n + 1).times do |i| s = i.to_s(2) s.each_char do |c| $bit[i] += 1 if c == "1" end end process(1, 1) if $min < 99999999 puts $min else puts -1 end