191. Number of 1 Bits、
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
Credits:
Special thanks to @ts for adding this problem and creating all test cases
Solution
Approach #1 (Loop and Flip) [Accepted]
核心思想:利用位运算和与运算,时间复杂度取决于位数
Approach #2 (Bit Manipulation Trick) [Accepted]
核心思想:n与n-1与 least siignificant 位置不断左移,一点点消去,利用1的借位
