??途W(wǎng)(java實(shí)現(xiàn))
問(wèn)題描述:
輸入一個(gè)整數(shù),輸出該數(shù)二進(jìn)制表示中1的個(gè)數(shù)。其中負(fù)數(shù)用補(bǔ)碼表示。
問(wèn)題分析:
(用位運(yùn)算實(shí)現(xiàn))
不斷清除n的二進(jìn)制表示中最右邊的1,同時(shí)累加計(jì)數(shù)器,直至n為0
算法實(shí)現(xiàn):
略
參考代碼:
public class Solution {
public int NumberOf1(int n) {
int sum = 0;
if (n == 0)
return 0;
while (n != 0)
{
sum++;
n = n&(n-1);
}
return sum;
}
}