1、方法一:
逐位判断;
作者:jyd
链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/solution/mian-shi-ti-15-er-jin-zhi-zhong-1de-ge-shu-wei-yun/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1 int hammingWeight(uint32_t n) { 2 int res=0; 3 while(n!=0) 4 { 5 res+=n&1; 6 n>>=1; 7 } 8 return res; 9 }
1 int hammingWeight(uint32_t n) { 2 int res=0; 3 while(n!=0) 4 { 5 res++; 6 n&=(n-1); 7 } 8 return res; 9 }