给定一个正整数 n,你可以做如下操作:
1. 如果 n 是偶数,则用 n / 2替换 n。
2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。
n 变为 1 所需的最小替换次数是多少?
示例 1:
输入:
8
输出:
3
解释:
8 -> 4 -> 2 -> 1
示例 2:
输入:
7
输出:
4
解释:
7 -> 8 -> 4 -> 2 -> 1
或
7 -> 6 -> 3 -> 2 -> 1
思路:3比较特殊,单独处理,偶数很简单,奇数的话加1可以除开4的,加一,否则减一
class Solution {
public int integerReplacement(int m) {
int sum=0;
int i;
long n=m;
while(n!=1)
{
if((n&1)==0)
{
n = (n>>1);
sum+=1;
}
else if((n&1)==1&&(n&2)==0)
{
n = n-1;
sum+=1;
}
else if((n&1)==1&&(n&2)!=0)
{
if(n==3)
{
sum+=2;
break;
}
else
{
n = n+1;
sum+=1;
}
}
}
return sum;
}
}
定义为long是因为输入2147483647时int类型再加一就溢出
还有另一种方法,把这个值单独判断
class Solution {
public int integerReplacement(int n) {
int sum=0;
int i;
while(n!=1)
{
if(n==2147483647)
{
n-=1;
continue;
}
if((n&1)==0)
{
n = (n>>1);
sum+=1;
}
else if((n&1)==1&&(n&2)==0)
{
n = n-1;
sum+=1;
}
else if((n&1)==1&&(n&2)!=0)
{
if(n==3)
{
sum+=2;
break;
}
else
{
n = n+1;
sum+=1;
}
}
}
return sum;
}
}