Sword refers to the number of 1 in offer-binary

Source: Internet
Author: User

Topic:

Implement a function, enter an integer, and output the number of 1 in the binary representation. As the binary of 9 is 1001, so input 9 output 2.


Solution one: Possible dead loops

int num1 (int n) {     int count =0;     while (n)     {         if (n&1) count++;         n=n>>1;      }      return count;}

The above function if you enter a negative number, if you have been doing the right operation, the final figure will become 0xFFFFFFFF and into a dead loop.


Solution Two: No dead cycle but low efficiency

int num1 (int n) {     int count =0;     unsigned int flag=1;     while (flag)     {         if (n&flag) count++;         flag=flag<<1;      }      return count;}

The number of cycles equals the number of digits in the integer binary, and 32-bit integers need to be looped 32 times.


Solution Three: There are several 1 only need to cycle several times

int num1 (int n) {     int count =0;     while (n)     {         ++count;         N= (n-1) &n;      }      return count;}


Sword refers to the number of 1 in offer-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.