翻转数位(思路挺好)

在这里插入图片描述
我觉得这道题挺好。

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;

    }
};

猜你喜欢

转载自blog.csdn.net/ShenHang_/article/details/107451829