If I want to give you a binary 1101101010101, I will ask you how much it is to convert it into a 10-digit system. The first thing I think of is to use the k power of 2.
In fact, we don't need to use the following code at all. ------- we assume that we accept this binary string. we generally do the same.
1 for( int i = 0 ; str[i]!=‘\0‘ ; i++ )2 {3 sum = sum*2 + str[i] - ‘0‘;4 }
We achieved K power through this * 2 because I = 0 is exactly the highest bit in binary.
Similarly, if I want to give you a decimal number of 23421, what is the quick way to convert it into a binary number?
We use Val to represent this decimal number and store the converted binary sequence in the STR string array.
1 while(n) 2 { 3 str[cnt++] = (n&1)+‘0‘; 4 // str[cnt++] = n%2+‘0‘; 5 n >>=1; 6 } 7 for( int i = cnt-1 ; i>=0 ; i-- ) 8 { 9 cout << str[i];10 }
There can be two ways to write N & 1 and N % 2. The speed of writing the former is faster, but do not forget the brackets according to the operator priority.
Also, the output order is backward. Do not make a mistake =-=.
I think this may be useful in the game.
Today:
Like is arrogant, but love is restrained
I have not read this sentence yet
What does this love mean?