问题:
Given a positive integer n and you can do operations as follow:
- If n is even, replace n with
n/2
. - If n is odd, you can replace n with either
n + 1
orn - 1
.
What is the minimum number of replacements needed for n to become 1?
Example 1:
Input: 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1
Example 2:
Input: 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1
解决:
① 递归解决。
class Solution {//7ms
public int integerReplacement(int n) {
long num = n;//避免栈溢出
return helper(num);
}
public int helper(long n){
if(n == 1) return 0;
if(n == 3) return 2;
if(n % 2 == 0){
return helper(n / 2) + 1;
}else{
return Math.min(helper(n + 1),helper(n - 1)) + 1;
}
}
}
②
利用bit位的操作。如果这个数偶数,那么末位的bit位一定是0。如果一个数是奇数,那么末位的bit位一定是1。对于偶数,操作是直接除以2。
对于奇数的操作:
如果倒数第二位是0,那么n-1的操作比n+1的操作能消掉更多的1。
1001 + 1 = 1010
1001 - 1 = 1000
如果倒数第二位是1,那么n+1的操作能比n-1的操作消掉更多的1。
1011 + 1 = 1100
1111 + 1 = 10000还有一个tricky的地方是,为了防止integer越界,可以将n先转换成long。long N = n;这样的处理。
class Solution { //6ms
public int integerReplacement(int n) {
long num = n;
int count = 0;
while(num != 1){
if (num % 2 == 0){
num = num >> 1;
}else {
if (num == 3){
count += 2;
break;
}
num = (num & 2) == 2 ? num + 1 : num - 1;
}
count ++;
}
return count;
}
}
③ 在discuss中看到的。
class Solution {//4ms
public int integerReplacement(int n) {
int count = 0;
if(n <= 1) return count;
while(n != 1){
if(n % 2 == 0){
n >>>= 1;
}else{
if(n == 3 || Integer.bitCount(n + 1) > Integer.bitCount(n - 1)){
n -= 1;
}else{
n += 1;
}
}
count ++;
}
return count;
}
}