Bit operations:
Shift left: M<<n m to the left N-position, left-shift post-low 0;
Shift right: m>>n m to the right of N-bit, the right shift after the high-level supplement is the sign bit, negative Supplement 1, Integer supplement 0. (Positive boundary value is (1,OX7FFFFFFF), negative value is (OX80000000,OXFFFFFFFF))
Topic One: Please implement a function, enter an integer, output this number of binary representation of the number of 1.
Idea one: The binary number I and 1 phase, determine whether it is 1, then tag=1 left one to get tag=2, and then with I and, the condition of the end of the loop is tag==0; the time complexity of the algorithm is the number of bits of input I.
#include <iostream>using namespace Std;int numberOf1 (int n) {int count=0;int tag=1;while (tag) {if (tag&n) count ++;tag=tag<<1;} return count;} void Main () { int i; while (cin>>i) {cout<<numberof1 (i) <<endl;}}
Thought two: The integer n minus 1, and then the original integer and the operation, the integer will be the rightmost 1 into 0, then, an integer binary in the number of 1, how many times such operations can be done. The condition for the end of the loop is n 0;
#include <iostream>using namespace Std;int numberOf1 (int n) {int count=0;while (n) {++count;n= (n-1) &n;} return count;} void Main () { int i; while (cin>>i) {cout<<numberof1 (i) <<endl;}}
Topic Two: Use a statement to determine whether an integer is 2 of the whole number of squares.
Idea: An integer if it is 2 of the whole number of squares, then its binary representation has only one bit is 1, and all the other bits are 0, according to the above analysis, the integer minus 1 and then with oneself, the only 1 will become 0.
Topic Three: Enter two integers m and n, calculate the number of n that need to be changed to get M.
The first step is to start with the M and N xor, then the number 1.
Topic Four: In Excel2003, use a to denote the first column, B for the second column, and C for the third column .... Use z for column 26th, AA for column 27th, and AB for column 28th ..... And so on, write a function to enter a letter representing the column number, and the output is the first column. (Problem with decimal conversion to 26 binary)
The bit operation of the offer-algorithm (number of 1 in binary)