• ㊗️
• 大家
• offer
• 多多！

## Problem

Given a positive integer n, you can apply one of the following operations:

1. If n is even, replace n with n / 2.
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


## Code

class Solution {
int res = Integer.MAX_VALUE;
public int integerReplacement(int n) {
helper((long)n, 0);
return res;
}

private void helper(long n, int count) {
if(n < 1) return;

if(n == 1) {
res = Math.min(res, count);
return;
}

if ((n & 1) != 0) {
helper(n + 1, count + 1);
helper(n - 1, count + 1);
} else {
helper(n >> 1, count + 1);
}
}
}


15 -> 16 -> 8 -> 4 -> 2 -> 1

15 -> 14 -> 7 -> 6 -> 3 -> 2 -> 1

7: +1和-1的结果相同

• 111 -> 110 -> 11 -> 10 -> 1
• 111 -> 1000 -> 100 -> 10 -> 1

3: -1

• 11 -> 10 -> 1
• 11 -> 100 -> 10 -> 1
class Solution {
public int integerReplacement(int n) {
if (n == Integer.MAX_VALUE) return 32; // n = 2^31-1
int count = 0;
while (n > 1){
if (n % 2 == 0) {
n /= 2;
} else {
// (n + 1) % 4 == 0
if ((n & 2) != 0 && (n != 3)) {
n++;
} else {
n--;
}
}
count++;
}
return count;
}
}