Integer Replacement Problem
Description
LeetCode Problem 397.
Given a positive integer n,you can apply one of the following operations:
- If n is even, replace n with n / 2.
- If n is odd, replace n with either n + 1 or n - 1.
Return the minimum number of operations needed for n to become 1.
Example 1:
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1
Example 2:
Input: n = 7
Output: 4
Explanation: 7 -> 8 -> 4 -> 2 -> 1
or 7 -> 6 -> 3 -> 2 -> 1
Example 3:
Input: n = 4
Output: 2
Constraints:
- 1 <= n <= 2^31 - 1
Solution
Approach: Greedy on the Last Two Bits
Halving is the only move for an even number, and it removes one bit. The only real choice is for odd n: go to n - 1 or n + 1. Both are even, so the next move halves either way. Pick the neighbor that is divisible by 4, because then it can be halved at least twice in a row:
n % 4 == 1(binary ends in01):n - 1ends in00, so go down.n % 4 == 3(binary ends in11):n + 1ends in00, so go up. Adding 1 turns the whole run of trailing ones into zeros, which is faster than removing them one at a time.- The one exception is
n = 3:3 → 2 → 1takes 2 steps, while3 → 4 → 2 → 1takes 3.
Repeat until n is 1, counting the steps.
The detail people get wrong is overflow: for n = 231 - 1, n + 1 does not fit in a 32-bit int. Java and C++ copy n into a 64-bit variable first (Python, JavaScript and Go's int already hold it).
Complexity: O(log n) time, since every two steps at least halve n, and O(1) space.
class Solution:
def integerReplacement(self, n: int) -> int:
steps = 0
while n != 1:
if n % 2 == 0:
n //= 2
elif n == 3 or n % 4 == 1:
n -= 1 # n - 1 is divisible by 4 (or n is 3: 3 -> 2 -> 1)
else:
n += 1 # n ends in binary 11: n + 1 is divisible by 4
steps += 1
return steps
Now write it from memory
Close the write-up and solve it yourself against the tests.