
-
1.解法1
int NumberOf1(int n){
int count = 0;
unsigned int flag = 1;
while(flag){//當flag中的1移到越界後,flag值會轉變為0
//當n&flag不為0時,表示目前flag中1對應的位置不為0
if(n&flag)count++;
flag = flag<<1;
}
return count;
}
-
2.解法2
int NumberOf1(int n){
int count=0;
while(n){
count++;
n = n&(n-1);
}
return count;
}