365. 二进制中有多少个1
计算在一个 32 位的整数的二进制表示中有多少个 1
.
样例
给定 32
(100000),返回 1
给定 5
(101),返回 2
给定 1023
(1111111111),返回 10
挑战
If the integer is n bits with m 1 bits. Can you do it in O(m) time?
// https://www.lintcode.com/problem/count-1-in-binary/description?_from=ladder&&fromId=6
class Solution {
public:
/*
* @param num: An integer
* @return: An integer
*/
int countOnes(int num) {
// write your code here
int result=0;
for(int i=0;i<32;i++)
{
result+=(num&1);
num=num>>1;
}
return result;
}
};
class Solution:
"""
@param: num: An integer
@return: An integer
"""
def countOnes(self, num):
# write your code here
result=0
for i in range(32):
result+=(num&1)
num=num>>1
return result