Reverse bits of a given the unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represent Ed in binary as00111001011110000010100101000000).
Title: To an unsigned 32-bit integer, reverse the binary representation (for example, 6, binary is 110, upside is 011, the corresponding 10-decimal integer is 3). Returns the decimal integer after the reversal.
The procedure is simple, for a given number, starting from the lowest bit, separating it, the lowest bit is the highest bit of the answer. Loop 32 times, dividing the number of inputs by 2 each time, and multiplying the answer by 2.
The problem is that the program runs as fast as possible, and I do 2 solutions, one using a bitwise operation to separate the last number, and one to separate by taking the remainder. As a result, I was surprised that the computation of the remainder was faster than the bitwise operation.
classSolution { Public: uint32_t reversebits (uint32_t N) {uint32_t ans=0; intbit =0; inti =0; while(I++ < +) {bit= n%2;//determine whether the last number is 0 or 1 by taking the remainderAns = ((ans <<1) +bit); N= N >>1; } returnans; }};classSolution { Public: uint32_t reversebits (uint32_t N) {uint32_t ans=0; for(inti =0; I < +; i++) {ans<<=1; Ans|= (N &1);////The last 1 bits are obtained by bitwise operation, plus the original numberN >>=1; } returnans;};
Leetcode-reverse Bits