二进制中1的个数

Posted on 2016-04-05 13:48  徐岩  阅读(120)  评论(0)    收藏  举报

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
 
Solution 1:
class Solution {
public:
     int  NumberOf1(int n) {
         bitset<32> bit(n);
         return bit.count();
     }
};
Solution 2: (不太懂)
class Solution {
public:
     int NumberOf1(int n) {
        int count = 0;
        while(n!= 0){
            count++;
            n = n & (n - 1);
        }
        return count;
     }
};