Number of 1 Bits

 1 typedef unsigned int uint32_t;
 2 class Solution {
 3 public:
 4     int hammingWeight(uint32_t n) {
 5         int tot=0;
 6         while(n)
 7         {
 8             tot+=n%2;
 9             n>>=1;
10         }
11         return tot;
12     }
13 };
View Code

 这是一道微软的面试题,判断末位是否为1 ,可以用&运算,官方答案是n&(n-1),判断是否为0 ,可以用n&(-n)

原文地址:https://www.cnblogs.com/varcom/p/4564789.html