[Statement: This article is only intended for self-Summary and mutual communication, and may be omitted. Email: Mr_chenping@163.com]
Question:
Enter an integer. Calculate the number of 1 in the Binary Expression of the integer. For example, input 10. Because the Binary Expression is 1010 and there are two 1 s, Output 2.
Question Analysis:
Solution 1: calculate the number of BITs as 1 from the right: Use the right shift operator to first determine whether the rightmost operator is 1 and then shift one to the right. It repeats until the input value changes to 0.
Solution 2: calculate the number of BITs as 1 from the left side. Another idea is that if an integer is not 0, at least one of the integers is 1. If we subtract 1 from this integer, the first 1 on the rightmost side of the integer will become 0, and the first 0 after 1 will become 1. All other bits will not be affected
Algorithm Implementation:
# Include
/*** Calculate the number of bits 1 from the rightmost */int count_bit_1 (int m) {int count = 0; while (m) {if (m & 1) count ++; m = m> 1;} return count ;}/ *** calculate the number of bits 1 from the leftmost */int count_bit_2 (int m) {int count = 0; while (m) {count ++; m = (m-1) & m;} return count ;} int main (int argc, char * argv []) {int m = atoi (argv [1]); printf ("% d -- method one ---> % d \ n", m, count_bit_1 (m); printf ("% d -- method two ---> % d \ n", m, count_bit_2 (m); return 0 ;}