Leetcode Note: Reverse Bits
I. Description
Reverse bits of a given32Bits unsigned integer.
For example, given input43261596(Represented in binary00000010100101000001111010011100), Return964176192(Represented in binary00111001011110000010100101000000).
Ii. Question Analysis
The requirement of the question is relatively simple. Enter a 32-bit unsigned integer and output an unsigned integer relative to the binary according to its binary representation. An example is provided.
This problem can be solved by using basic bitwise operations. Of course, a clever method is also proposed on the Internet, which provides such a method for bitwise operations, the digits are flipped by the entire block. For example, 32 digits are divided into two 16-digit digits, and 16 digits are divided into two 8-digit digits for flip, and so on.
For an 8-bit numberabcdefghThe process is as follows:
abcdefgh -> efghabcd -> ghefcdab -> hgfedcba
Further discussion:
Remember how merge sort works? Let us use an example of n = 8 (one byte) to see how this works:
01101001 / \ 0110 1001 / \ / \ 01 10 10 01 /\ /\ /\ /\0 1 1 0 1 0 0 1
The first step is to swap all odd and even bits. After that swap consecutive pairs of bits, and so on...
Therefore, only a total of log (n) operations are necessary.
The below code shows a specific case where n = 32, but it cocould be easily adapted to larger n's as well.
Iii. Sample Code
Class Solution {public: uint32_t reverseBits (uint32_t n) {uint32_t result = 0; if (n = result) return result; int index = 31; // At the beginning, the nth percentile must shift 31 to the highest percentile while (n) {result | = (n & 0x1) <index; // obtain the nth percentile, and move right to the high position -- index; // the number of shifts right to keep the symmetry n> = 1;} return result ;}};
// Another clever practice/* 0x55555555 = 0101 0101 0101 0101 0101 0101 0101 01010 1010 xAAAAAAAA = 1010 1010 1010 1010 1010 1010 10100x33333333 = 0011 0011 0011 0011 0011 0011 0011 00110 xCCCCCCCC = 1100 1100 1100 1100 1100 1100 1100 1100 */class Solution {public: uint32_t reverseBits (uint32_t n) {uint32_t x = n; x = (x & 0x55555555) <1) | (x & 0 xAAAAAAAA)> 1 ); x = (x & 0x33333333) <2) | (x & 0 xCCCCCCCC)> 2); x = (x & 0x0f0f0f) <4) | (x & 0xF0F0F0F0)> 4); x = (x & 0x00FF00FF) <8) | (x & 0xFF00FF00)> 8 ); x = (x & 0x0000FFFF) <16) | (x & 0xFFFF0000)> 16); return x ;}};
Iv. Summary
It is not difficult to meet the requirements of this question, but the wonderful practices are very eye-catching.