[LeetCode] 191. Number of 1 Bits
Question
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 shocould return 3.
Ideas
Move one digit left each time and perform the operation.
Code
/* Author * Date: * Author: SJF0115 * Subject: 191. Number of 1 Bits * URL: Response result: AC * Source: LeetCode * blog: Author */# include
# Include
Using namespace std; class Solution {public: int hammingWeight (uint32_t n) {if (n = 0) {return 0 ;}// if (n = 1) {return 1 ;}// if int count = 0; for (int I = 0; I <32; ++ I) {if (n & (1 <
0) {++ count ;}// if} // for return count ;}; int main () {Solution solution; uint32_t num = 1; cout <"<
Train of Thought 2
Every time x = x & (x-1) is executed, a 1 on the rightmost side of x is changed to 0 when x is represented in binary, because the X-1 will change this bit (A 1 on the rightmost when x is represented in binary) to 0.
Code 2
/* Author * Date: * Author: SJF0115 * Subject: 191. Number of 1 Bits * URL: Response result: AC * Source: LeetCode * blog: Author */# include # Include Using namespace std; class Solution {public: int hammingWeight (int n) {int count = 0; while (n! = 0) {n = n & (n-1); count ++ ;}// while return count ;}; int main () {Solution solution; uint32_t num = 11; cout <"" <