輸入一個整數,輸出該數二進制表示中1的個數。其中負數用補碼錶示
public class Solution {
public int NumberOf1(int n) {
int count = 0;
//n是正數
while(n > 0){
n &= (n - 1);
count++;
}
//n是負數,也可以用一個while(n != 0)包含正負兩種情況
while(n < 0){
n &= (n - 1);
count++;
}
return count;
}
}