191. Number of 1 Bits Posted on 2021-01-19 Edited on 2021-01-25 In LeetCode Disqus: Symbols count in article: 343 Reading time ≈ 1 mins. 常规数1法 1234567891011class Solution {public: int hammingWeight(uint32_t n) { int res = 0; while (n > 0) { res += (n & 1); n >>= 1; } return res; }}; 翻转最后一个1法这个比较通用,不受n正负的影响 1234567891011class Solution {public: int hammingWeight(uint32_t n) { int res = 0; while (n > 0) { ++res; n &= (n - 1); // 把最低位的1变成0 } return res; }};