Write a function that takes an unsigned integer and returns the number of ' 1 ' bits it has (also known as the Hamming weigh T).
For example, the 32-bit integer ' One ' have binary representation 00000000000000000000000000001011, so the function should re Turn 3.
Solving Ideas 1
Each digit and 1 are performed and calculated, and the statistic result is not 0 digits.
Implementation Code 1
//runtime:10 Ms#include <iostream>#include "inttypes.h"using namespace STD;classSolution { Public:intHammingweight (uint32_t N) {inti =0; while(n) {i + = n &0x1; N >>=1; }returnI }};intMain () {solution S;cout<<s.hammingweight ( One) <<endl;return 0;}
Solving Ideas 2
Each time n& (n-1) can reduce the number of bits in n by a value of 1 to one
Implementation Code 2
//Runtime:11 msclass Solution {public: inthammingWeight(uint32_t n) { int0; while (n) { n &= (n-1); ++i; } return i; }};
[Leetcode] Number of 1 Bits