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
分析如下:
https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations
结论:1.如果n是偶数 折半
2 如果n=3或者n-1中的1的位数比n+1中1的位数少那么n-1
3其余情况n+1
补充java方法: Integer.bitCount(int n) 返回n(二进制)中1的位数
>> 右移一位 <<左移一位 >>>忽略符号位右移一位, 用0补齐 此处需用这个! 否则会溢出2147483647
public int integerReplacement(int n) {
int c = 0;
while (n != 1) {
if ((n & 1) == 0) {
n >>>= 1; //这个地方要用n>>>1 如果用n=n/2 出现溢出问题 需要考虑?
} else if (n == 3 || Integer.bitCount(n + 1) > Integer.bitCount(n - 1)) {
--n;
} else {
++n;
}
++c;
}
return c;
}
public int integerReplacement(int n) {
int c = 0;
while (n != 1) {
if ((n & 1) == 0) {
n >>>= 1;
} else if (n == 3 || ((n >>> 1) & 1) == 0) { //留意后两位 奇数是最后一位是1 如果倒数第二位是0那么减1 使得1的位数更少
--n;
} else {
++n;
}
++c;
}
return c;
}