码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Count 1 in Binary

时间:2015-08-15 10:20:08      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

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?

常规解法:

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

使用STL的解法: 

#include <bitset>
class Solution{
public:
/**
* @param num: an integer
* @return: an integer, the number of ones in num
*/
int countOnes(int num) {
// write your code here
bitset<sizeof(int)*8> bitvec(num);
return bitvec.count();
}
};

 

 

[LintCode] Count 1 in Binary

标签:

原文地址:http://www.cnblogs.com/changchengxiao/p/4731863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!