Integer Replacement

MediumBit Manipulationbit manipulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a positive integer n, you may repeatedly apply one of these operations: - if n is even, replace it with n / 2; - if n is odd, replace it with either n + 1 or n - 1. Return the minimum number of operations needed to turn n into 1. Note that n + 1 can exceed the signed 32-bit range when n = 2^31 - 1; languages with fixed-width integers should use a 64-bit type internally.

Examples

Input: n = 8
Output: 3
8 -> 4 -> 2 -> 1.
Input: n = 7
Output: 4
7 -> 8 -> 4 -> 2 -> 1 (or 7 -> 6 -> 3 -> 2 -> 1).

Constraints

  • 1 <= n <= 2^31 - 1
  • Intermediate values may reach 2^31
  • Only the three listed operations are allowed

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bit manipulation problems