解法一:讓臨時變量每次乘以二再與源數字相與,測試每一位上的數字是否爲1
public int NumberOf1(int n) {
int temp=1,count=0;
while(temp!=0){
if((temp&n)!=0){
count++;
}
temp=temp<<1;
}
return count;
}
解法二:將原來的數字減一再與源數相與,爲0則說明該位爲0,不爲0 則說明該爲不爲0數字中有多少個1 就循環多少次
public int NumberOf1(int n) {
int temp,count=0;
while(n!=0){
temp=n-1;
n=temp&n;
if(n!=0){
count++;
}
}
return count;