leetcode No.190,191颠倒二进制位;位1的个数

No.190

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
//二进制左移一位,右边补0,相当于乘2;右移一位,正数左边补0,负数左补1,最右边丢弃一位
    //每一位&1的结果相当于读取该位 
        int result=0;
        int i=32;
        while(i>0){
            result<<=1; //左移一位  右边补0
            result=result+(n&1); //n和000..001相与,获取当前最后一位放到补0后的位置上
            n>>=1; //右移 以便下次获取下一位
            --i;
        }
        return result;
    }
}

No.191

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int nums=0;
        int i=32;
        while(i-->0){
            if((n&1)==1)
                ++nums;
            n>>=1;
        }
        return nums;
    }
}

No191 评论区另一种思路 C++

//技巧:直接去掉二进制中位置最靠后的1
//可以分情况讨论n末尾是1还是0来验证这个算法
int hammingWeight(uint32_t n) {
        int ans=0;
        while(n) //当n不为0
        {
            ans++;  //直接先加一
            n&=n-1; //每一次这个运算都会消除最后的一个1,直到没有1,退出循环
        }
        return ans;
    }

猜你喜欢

转载自blog.csdn.net/qq_33399567/article/details/89023304