题意
一个数n, 若为偶数, 则除2, 若为奇数, 则加减1; 求其最终为1, 需要几步
方法
位运算
代码
class Solution {
public:
int integerReplacement(int n) {
if(n==1) return 0;
int result=0;
while((n&1)==0)
{
++result;
n=n>>1;
}
if(n==1)
{
return result;
}
int judge=1,temp=0;
while((judge&n)==judge)
{
++temp;
judge=judge<<1;
}
int p=n>>temp;
int first=(p==0)?2*(temp-1):integerReplacement(p)+2*(temp);
int second=integerReplacement(p|1)+temp+1;
return result+min(first,second);
}
};
标签:return,temp,int,LeetCode397,integerReplacement,result,judge,Integer,Replacement
From: https://www.cnblogs.com/Figure_at_a_Window/p/16953409.html