劍指offer-11:二進位制中1的個數
阿新 • • 發佈:2018-12-05
題目描述
輸入一個整數,輸出該數二進位制表示中1的個數。其中負數用補碼錶示。
思路
用1(1自身左移運算,其實後來就不是1了)和n的每位進行位與,來判斷1的個數
程式碼
public class Solution11 {
public int NumberOf1(int n) {
int count = 0;
int flag = 1;
while (flag != 0) {
if ((n & flag) != 0) {
count++;
}
flag = flag << 1;
}
return count;
}
public static void main(String[] args) {
Solution11 solu=new Solution11();
System.out.printf("%d",solu.NumberOf1(-32));
}
}
另一種最優解:
思路
如果一個整數不為0,那麼這個整數至少有一位是1。如果我們把這個整數減1,那麼原來處在整數最右邊的1就會變為0,原來在1後面的所有的0都會變成1(如果最右邊的1後面還有0的話)。其餘所有位將不會受到影響。
程式碼
public class Solution11 {
public int NumberOf1(int n) {
int count = 0;
while(n!= 0){
count++;
n = n & (n - 1);
}
return count;
}
public static void main(String[] args) {
Solution11 solu=new Solution11();
System. out.printf("%d",solu.NumberOf1(-32));
}
}