剑指offer 面试题15. 二进制中1的个数 [简单]

我的解题:

1.将输入的整数逐位与1相与

    int hammingWeight(uint32_t n) {
        int count=0;
        while(n){    
            for(int i=0;i<32;i++){
                if(n&(1<<i)) count++;
            }
        }
        return count;
    }
};

2.n&(n-1)可以消除n最低位的1

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count=0;
        while(n){
            n&=n-1;
            count++;
        }
        return count;
    }
};

发布了76 篇原创文章 · 获赞 1 · 访问量 585

猜你喜欢

转载自blog.csdn.net/qq_41041762/article/details/105585333