LintCode_365 Count 1 in Binary

Count how many 1 in binary representation of a 32-bit integer.

Example

Given 32, return 1

Given 5, return 2

Given 1023, return 9

Challenge 

If the integer is n bits with m 1 bits. Can you do it in O(m) time?


主要是要記住最後一位爲1的取法


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 res = 0;
        while (num != 0) {
            res++;
            num&=(num - 1);
        }
        return res;
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章