# frozen_string_literal: true # rubocop:todo Metrics/PerceivedComplexity # rubocop:todo Metrics/CyclomaticComplexity # rubocop:todo Metrics/AbcSize def solve # rubocop:todo Metrics/MethodLength return 0 if N == 1 positions = [0] squares = Array.new(N, nil) squares[0] = 0 step = 1 N.times do new_positions = [] positions.each do |position| bit_count = BIT_COUNTS[position + 1] left = position - bit_count right = position + bit_count return step + 1 if right == N - 1 if left >= 0 && (squares[left].nil? || squares[left] > step) squares[left] = step new_positions << left end if right <= N - 1 && (squares[right].nil? || squares[right] > step) squares[right] = step new_positions << right end end positions = new_positions step += 1 end -1 end # rubocop:enable Metrics/AbcSize # rubocop:enable Metrics/CyclomaticComplexity # rubocop:enable Metrics/PerceivedComplexity N = gets.to_i BIT_COUNTS = (0..N).map { _1.digits(2).sum } puts solve