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.