(LeetCode OJ) Number of 1 Bits (191]
191. Number of 1 Bits
QuestionTotal Accepted: 65438 Total Submissions: 172909 Difficulty: Easy
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 representation00000000000000000000000000001011, So the function shocould return 3.
Credits:
Special thanks to @ ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags Bit Manipulation Hide Similar Problems (E) Reverse Bits (E) Power of Two
// Clear thinking: first, this number is a positive integer, and the question is clear. // certain situations: as long as this number is not 0, it will have 1 // reduce the leftmost binary 1 in each loop --- "n = n & n-1 // For example, if there are 5 1 s, it will be cyclically 5 times (reduce 5 times) class Solution {public: int hammingWeight (uint32_t n) {int cnt = 0; while (n) {cnt ++; n = n & n-1; // reduce the leftmost 1} return cnt ;}} in the binary ;}};