LeetCode -- Number of 1 Bits
題目描述:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
本題依然屬於一道位運算的題目,輸入一個無符號的整數,判斷出1的個數。
思路:
對於整數n,從n開始對n和n-1做與運算然後賦值給n。即,n=n&n-1。直到n等於n為止。能做多少次運算就說明有多少個1。
實現代碼:
public class Solution {
public int HammingWeight(uint n) {
int count;
for (count=0; n > 0 ; count++){
n &= n-1;
}
return count;
}
}