Number of 1 in binary

Source: Internet
Author: User

Problem Description:

Implement a function, enter an integer, and output the number of 1 in the binary representation.

Thinking Analysis:

Simple immediately think of the number of times to move right, as long as the 1 and the words can be counted, but the displacement of negative numbers left in order to maintain the sign bit will

Fill one, for example, move 1101 to the right to turn 1110. This will cause a dead loop.

Here are two possible ways to do this:

1, we can not right-shift the input array n, first to do the N and 1 with the operation, to determine whether the lowest bit is 1, then the 1 left one to get 2 again and

n Doing and arithmetic, we can judge whether the second low of n is 1. So that the left shift can be repeated n each of them is not 1. The number of cycles is two of n

Number of bits in the system

2, we found that an integer minus 1, is the last 1 to 0, if it has 0 on the right, all 0 becomes 1, and it left

All the bits on the side remain the same. For example, subtract 1100 minus 1 to get 1011. Sum up the above analysis: Subtract an integer by 1,

And the original integer to do with the operation, the integer will be the rightmost one 1 into 0, then a binary number of how many 1, you can do how much

This operation. This reduces the number of cycles compared to the above.

Reference code:

int NumberOf1 (int n)
{
unsigned int flag = 1;
int ncount = 0;

while (flag)
{
if ((N & flag)! = 0)//here to judge the conditions to be noted
{
ncount++;
}
Flag = flag<<1; So how many bits of n do you need to move left?
}
return ncount;
}

int NumberOf1 (int n)
{
int ncount = 0;
while (n)
{
++ncount;
n = (n-1) &n;
}
return ncount;
}

Thinking: bit operation is not difficult, some rules to understand clearly the writing process is very convenient, the following will find some of the problem of the bit operation.

Number of 1 in 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.