lintcode-easy-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?

不知道怎么做challenge……

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

 

posted @ 2016-02-24 13:59  哥布林工程师  阅读(103)  评论(0编辑  收藏  举报