問題
編寫一個函數,輸入是一個無符號整數,返回其二進制表達式中數字位數爲 ‘1’ 的個數
例子
思路
-
方法1 O(logn)
-
方法2
代碼
//方法1
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count=0;
while(n!=0){
count+=n&1;
//無符號右移:不管正負,高位補0
n=n>>>1;
}
return count;
}
}
//方法2