Count 1 in Binary

class Solution {
public:
    /**
     * @param num: an integer
     * @return: an integer, the number of ones in num
     */
    int countOnes(int num) {
        // write your code here
        int count = 0;
        for(int i = 0; i < 32; ++i){
            int mask = (1 << i);
            if ((num & mask) !=0){
                ++count;
            }
        }
        return count;
    }
};

方法二:

class Solution {
public:
    /**
     * @param num: an integer
     * @return: an integer, the number of ones in num
     */
    int countOnes(int num) {
        int count = 0;
        for (; num; num &= num - 1) {
            ++count;
        }
        return count;
    }
};

num & (num -1) 一直就把最后一个非0位变成1, 一直变到所有的都是0, 那么process了几次, 就是有几位1

 

posted on 2016-07-19 11:11  codingEskimo  阅读(101)  评论(0编辑  收藏  举报

导航