计算在一个 32 位的整数的二进制表式中有多少个 1.
样例
给定 32 (100000),返回 1
给定 5 (101),返回 2
给定 1023 (111111111),返回 9
class Solution {
public:
/**
* @param num: an integer
* @return: an integer, the number of ones in num
*/
deque<long long> tobinary(long long num){
deque<long long> d;
if(num<0){
num=4294967296+num;
}
while(num!=0){
//��
int rem=num%2;
//�
int res=num/2;
num=res;
d.push_back(rem);
}
return d;
}
int countOnes(long long num) {
// write your code here
int counts=0;
deque< long long> d=tobinary(num);
for(auto it=d.rbegin();it!=d.rend();it++){
// cout<<*it<<" ";
if((*it)==1){
counts++;
}
}
return counts;
}
};