Today, I started to read this book about the beauty of programming. I think it is good to read this book before. There is no time to read the project. Now it's a little easier to read the project. The last time I browsed this book, I decided to start from Chapter 2. Today I wrote the first part of Chapter 2: calculate the number of 1 in the binary number.
The book introduces many methods, which are very good!
First: the most direct solution, with % and /. If the remainder result is 1, add 1 to the count and divide it by 2. The source code is as follows:
# Include stdio. h> int main () {int num = 0; int v; scanf ("% d", & v); while (v) {if (v % 2 = 1) // judge the remainder result. If it is 1, the Count num is increased by 1 num ++; v/= 2;} printf ("% d/n", num ); return 0 ;}
The second method is to calculate the number of 1 in the binary number 7. The binary value of 7 is 0x0111, and 0x0111 is the same as 0x01. If the result is 1, this bit is 1; otherwise, it is 0. then shift 0x0111 to the right to complete the counting.
The source code is as follows:
# Include stdio. h> int main () {int num = 0; int v; scanf ("% d", & v); while (v) {num + = v & 0x01; // perform the & Operation on the last digit and 0x01. If the value is 1, the value of num increases by 1. Otherwise, the value of num remains unchanged. V >>> = 1; // shift v to the right by 1} printf ("% d/n", num); return 0 ;}
Third: You can determine whether the number is the power of the certificate 2. For example, if you want the operation result to be 0, 00111111, you can perform the "and" operation.
In this way, the operation to be performed is 01000000 & (01000000-00000001) = 01000000 & 00111111 = 0.
The source code is as follows:
#include stdio.h>int main(){ int num = 0; int v; scanf("%d",&v); while(v) { v &= v-1; num++; } printf("%d/n",num); return 0;}
Among the above three solutions, the third method is the most ingenious, and the time complexity is a constant.
The following is a related exercise:
Question: Given two integers A and B, how many digits do I need to change A to B? That is to say, how many bits are different in the binary representation of A and B?
This problem can be solved by referring to the second solution above. Perform and operate A and B with the same 0x01, and then determine whether the results of the two operations are the same. If they are different, add 1 to the counter. in this way, we can calculate how many BITs A and B are different.
The source code is as follows:
# Include stdio. h> int main () {int num = 0; int v, u; scanf ("% d", & v, & u); while (v & u) {if (v & 0x01 )! = (U & 0x01) // This digit in two numbers is different from num ++; v >>=1; // v shifts 1 bit u >>= 1; // u shifts 1 bit} printf ("% d/n", num); return 0 ;}