Evaluate the number of 1 in the binary of an integer

Source: Internet
Author: User

Question: enter an integer to calculate the number of 1 in the Binary Expression of this integer. For example, input 10. Because the binary value is 1010 and there are two 1 s, Output 2.

Assume that the integer is I. First, perform operations on I and 1 to determine if the I percentile is 1. Then, shift 1 to the left to get 2, and then perform operations with I to determine whether the secondary high of I is 1 ...... In this way, the Left shift is repeated, and each time you can judge whether one of the I is 1. Based on this, we get the following code:

Int numberof1_solution (int I) {int COUNT = 0; unsigned int flag = 1; while (FLAG) {if (I & flag) Count ++; flag = Flag <1;} return count ;}

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.