剑指 Offer 15. 二进制中1的个数

剑指 Offer 15. 二进制中1的个数,第1张

剑指 Offer 15. 二进制中1的个数 题目

二进制中1的个数

C++代码
class Solution {
public:
    int hammingWeight(uint32_t n){
        int res = 0;
        while(n){
            res++;
            n = n & (n - 1);
        }
        return res;
    }
};
Java代码
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n){
        int res = 0;
        while(n != 0){
            n = n & (n - 1);
            res++;
        }
        return res;
    }
}
联系方式

如果有任何问题可以邮箱联系我:[email protected]

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5698907.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存