The binary value of an integer indicates the number of values in 1.

Source: Internet
Author: User

I. Problem Description

Question 28: integer binary represents the number of 1
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.

 

Ii. Algorithm Description

This problem is quite basic and can be solved using the right shift operator: an integer expressed in binary, you can determine whether its parity is 1 by judging its parity, and then move one to the right, then judge whether it is 1; until this number is zero, it can be stopped.

 

Iii. Source Code

# Include <stdio. h> int count_one (INT value) {int result = 0; while (value) // exit the loop when value is zero {If (Value % 2 = 1) // if the value is an odd number, add 1 {result ++;} value = value> 1 to the number of one; // shift the value one to the right, except 2} return result;} int main () {int I; for (I = 0; I <32; I ++) {printf ("% d -- % d \ n", I, count_one (I);} return 0 ;}

 

Iv. Summary

A solid foundation is required. No matter what knowledge or skills you learn, this is the case. There must be a lot of people who understand this truth, but they can do less.

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.