Integer Replacement
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 neededProblem
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
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.