[LeetCode] 191. Number of 1 Bits

Source: Internet
Author: User

[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 <"" <   

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.