How many of the binary representations of an integer are 1

Source: Internet
Author: User

Topic:

An integer is stored in memory and outputs the number of 1 in the binary representation of it

Ideas:

To determine the number of 1 in the binary representation of this integer, it is the topic of the [bitwise operation].

The first thought of clever use [1] This number, [1] only the most right one is 1, the other bits are 0;

So, the next thing you should think of, with "1" and this integer to do [and operations], first of all, you can determine whether the rightmost bit is 1, and so on, the integer every right to move one bit, and 1 to do with the operation, Until the integer becomes 0. At this point, the problem of thinking has been, but consider the abnormal numbers, such as [negative], the method does not apply, because the negative binary needs to maintain the highest bit has been 1, and finally into the Dead Loop (OXFFFFFFFF) in front of the train of thought, two numbers and operations, that can let [1] left shift And the original integer does not move, so you can determine whether the secondary high is 1. With this [1] continue to move left.

There is another way of thinking, a not 0 integer i, at least one is 1, do such an operation:

The result of the i-1 is that the right side of the rightmost 1 of the integer I is all 0 of the bits are changed to 0, that is, after minus 1, all the bits after the rightmost 1 are reversed, and then I do the operation with it, and the result is that all the bits after the rightmost 1 are changed to 0, so, repeating such steps, How many times minus 1 of the operation, I of the binary representation of how many 1, until the number of times minus 1 I becomes 0.

Another: Clear the right-most 0 method:

i=i* (i-1)

How many of the binary representations of an integer are 1

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.