二进制中1的个数

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

下面这种方法只适用于正数,负数不适用,右移一位,对于负数来讲,左边补的是1。

class Solution {
public:
     int  NumberOf1(int n) {
         
      int count = 0;
        while(n != 0)
            {
            if((n & 1) == 1) count++;
            n >>= 1;
        }
        return count;
    }
};
View Code
class Solution {
public:
     int  NumberOf1(int n) {
         
        int count = 0;
        unsigned int num = n;
        while (num != 0) {
            if ((num & 1) == 1){
                count++;
            }
            num = num >> 1;
        }
         return count;
     }
};
View Code

负数右移动,左边补1。所以将负数转成正数,这样再计算1的个数即可。

使用下面这种方法

class Solution {
public:
     int  NumberOf1(int n) {
         
     int count = 0;
        while (n != 0) {
            ++count;
            n = (n - 1) & n;
        }
        return count;
    }
};
View Code

 

posted @ 2016-09-19 09:56  于光远  阅读(144)  评论(0编辑  收藏  举报