class Fixnum def bitcount self.to_s(2).chars.count('1') end end class Yukicoder UNKNOWN = -1 def initialize n = gets.chomp.to_i check_list = Hash.new(UNKNOWN) check_list[1] = 1 dist = 2 states = [1] while states.any? next_states = [] states.each do |s| move_dist = s.bitcount a = s - move_dist b = s + move_dist if a >= 1 && check_list[a] == UNKNOWN check_list[s - move_dist] = dist next_states << s - move_dist end if b <= n && check_list[b] == UNKNOWN check_list[s + move_dist] = dist next_states << s + move_dist end end states = next_states.dup dist += 1 end puts check_list[n] end end Yukicoder.new