題目:
輸入一個(gè)整數(shù),輸出該數(shù)二進(jìn)制表示中1的個(gè)數(shù)。其中負(fù)數(shù)用補(bǔ)碼表示
思路:
二進(jìn)制數(shù)每位挨個(gè)和 1 (左移后其實(shí)不是1了,如:000100 ) 做與(&)運(yùn)算,結(jié)果不是零則count++
public class Solution {
public int NumberOf1(int n) {
if(n == 0)
return 0;
int count = 0;
int temp = 1;
while(temp != 0){
if((temp & n) != 0)
count ++;
temp = temp << 1;
}
return count;
}
}
如果移位的不是 1 而是 n 的話,要注意負(fù)數(shù)(補(bǔ)碼)向右移位時(shí)最左端會(huì)補(bǔ)1,這樣就死循環(huán)了,解決方法時(shí)把 n = n >> 1 改成 n = n >>>1,">>>" 無視符號(hào)位移位
public class Solution {
public int NumberOf1(int n) {
if(n == 0)
return 0;
int count = 0;
while(n != 0){
if((n & 1) == 1)
count++;
n = n >>> 1; // 無視符號(hào)位右移
}
return count;
}
}