我觉得这道题挺好。
class Solution {
public:
int reverseBits(int num) {
int res=0;
int cur=0,prev=0;
//从低位开始
while(num)
{
if(num&1)
{
cur++;
}
else//当前bit是0
{
if(cur+prev+1>res)
{
res=cur+prev+1;
}
prev=cur;
cur=0;
}
num>>=1;
}
//别忘记最后还需要额外判断一次
if(cur+prev+1>res)
{
res=cur+prev+1;
}
return res;
}
};
class Solution {
public:
int convertInteger(int A, int B)
{
return convertInteger((unsigned int)A,(unsigned int)B);
}
int convertInteger(unsigned int A, unsigned int B) {
int t1,t2;
int count=0;
while(A||B)
{
t1=A&1;
t2=B&1;
if(t1!=t2)
count++;
A>>=1;
B>>=1;
}
return count;
}
};