public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
for(int i = 31; i >=0; i--){
count = count + n / (1 << i);
n = n % (1 << i);
}
return count;
}
}
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
for(int i = 31; i >=0; i--){
count = count + n / (1 << i);
n = n % (1 << i);
}
return count;
}
}
/* Note:Your choice is C IDE */
#include "stdio.h"
int count=0;
void tobin(int a,char* str){
char *p=(char*)&a,c=0,f=0,pos=-1;//p指向a的首地址
int o;
int i;
for(o=0;o<4;++o){
for(i=0;i<8;++i){
c=p[3-o]&(1<<(7-i));
if(!f&&!(f=c))
continue;
if(c){
count++;
}
str[++pos]=c?'1':'0';
}
}
}
void main()
{
int a= 10000;
char str[32]={0};
tobin(a,str);
printf("%s\n",str);
printf("count=%d\n",count);
}