zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[LeetCode]191. 位1的个数

LeetCode 个数
2023-09-11 14:18:49 时间

算法标签 位运算 汉明重量

题目简叙

在这里插入图片描述

思路

位运算
现存的值直接循环右移,检测二进制状态下各个位的值是0还是1

代码

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res=0;
        int str = (int)n;
        
        for(int i=0;i<32;i++)if(str>>i&1==1)res++;

        return res;
    }
};

AC记录

在这里插入图片描述