[LeetCode] Reverse Bits, leetcodereverse
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000 ).
This is an unsigned 32-bit integer that reverses the binary representation.
For example 6, if the binary value is 0000 0000 0000 0000 0000 0000 0000 0110 0110, the result is 0000 0000 0000 0000 0000 0000 0000.
The practice is very simple. For a given number, it is separated from the highest bit, and the lowest bit is the highest bit of the answer. Loop 32 times, multiply the separated number every time by 2 ^ I, I =, 2 ,..., 31
Paste the code below:
Class Solution {public: uint32_t reverseBits (uint32_t n) {int I = 32; uint32_t ans = 0; while (I --) {int bit = n> I & 0x1; ans + = bit * (1 <(31-i);} return ans ;}};