(LeetCode OJ) Number of 1 Bits (191]

Source: Internet
Author: User

(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 ;}};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.