I. Title Description
Reverse bits of a given 32
bits unsigned integer.
For example, given-input 43261596
(represented in binary 00000010100101000001111010011100
as), return 964176192
(represented in binary as 00111001011110000010100101000000
).
Two. Topic analysis
The requirements of the topic are relatively simple, enter a 32-bit unsigned integer, and, according to the binary representation, the output is a binary-relative unsigned integer. The topic also gives an example.
The problem using the basic bit operation can be solved, of course, the Internet also proposed a very ingenious method, wherein the bit operation has such a method, the number of bits in accordance with the whole block of the flip, such as 32 bits into two pieces of 16 bits of the number, 16 bits divided into two 8 bits to flip, and so on.
For a 8bit number abcdefgh
, the process is as follows:
abcdefgh -> efghabcd -> ghefcdab -> hgfedcba
Further elaboration, CC on-line explanation:
Remember How merge sort works? Let us use an example of n = = 8 (one byte) to see how the This works:
01101001 / 0110 1001 / \ / 01 10 10 01 /\ /\ /\ /0 1 1 0 1 0 0 1
The first step is to swaps all odd and even bits. After the swap consecutive pairs of bits, and so on ...
Therefore, only a total of log (n) operations is necessary.
The below code shows a specific case where n = =, but it could is easily adapted to larger N's as well.
Three. Sample code
class solution { Public: uint32_t reversebits (uint32_t N) {uint32_t result =0;if(n = = result)returnResultint Index= to;//initial n minimum bits need to move right 31 bits to highest bit while(n) {result |= (N &0x1) <<Index;//Take the lowest bit of N and move right to high--Index;//Right shift number, maintaining symmetryN >>=1; }returnResult }};
Another ingenious approach/*0x55555555=0101 0101 0101 0101 0101 0101 0101 01010xAAAAAAAA=1010 1010 1010 1010 1010 1010 1010 10100x33333333=0011 0011 0011 0011 0011 0011 0011 00110xCCCCCCCC=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 & 0xaaaaaaaa)>> 1); x =((x & 0x33333333)<< 2) |((x & 0xcccccccc)>> 2); x =((x & 0x0f0f0f0f)<< 4) |((x & 0xf0f0f0f0)>> 4); x =((x & 0x00ff00ff)<< 8) |((x & 0xff00ff00)>> 8); x =((x & 0x0000ffff)<< 16) |((x & 0xFFFF0000)>> 16); return x; }};
Four. Summary
It is not difficult to achieve this problem, but it is an eye-opener for the people of great practice.
Leetcode Note: Reverse Bits