二进制中有多少个1
计算在一个 32 位的整数的二进制表示中有多少个 1
.
给定 32
(100000),返回 1
给定 5
(101),返回 2
给定 1023
(111111111),返回 9
If the integer is n bits with m 1 bits. Can you do it in O(m) time?
public class Solution {
/*
* @param num: An integer
* @return: An integer
*/
public int countOnes(int num) {
// write your code here
int count =0;
int a=0;
int b=0;
int c=32;//当num=-1的时候,32位全是1,为了之后计算总共补多少1
if(num<0){//小于零的时候符号位补满1
int d=-num;
while(d>0){
b=d%2;
if(b==1){
count++;
}
d=d/2;
c=c-1;//每计算一次,前面补1的位数-1
}
return c+count;//1的多少等于num本身的1和符号位补的1的合
}
while(num>0){
a=num%2;
if(a==1){
count++;
}
num=num/2;
}
return count;
}
};