public int HammingWeight(uint n) { string s = Convert.ToString(n, 2); int count = 0; for (int i = 0; i < s.Length; i++) { if (s[i] == '1') { count++; } } return count; }
右移法:
1 2 3 4 5 6 7 8 9 10 11 12 13
public int HammingWeight(uint n) { int result = 0; for (int i = 0; i < 32; i++) { if ((n & 1) == 1) { result++; } n = n >> 1; } return result; }