1Reverse bits of a given, unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represent Ed in binary as 00111001011110000010100101000000).
Follow up:
If This function is called many times, what would you optimize it?
Solving Ideas 1
The procedure is similar to converting a string to shaping, except that it is binary and is processed from the right.
Implementation Code 1
//runtime:10 Ms#include <iostream>#include "inttypes.h"using namespace STD;classSolution { Public: uint32_t reversebits (uint32_t N) {uint32_t result =0;inti = +; while(i--) {result = result *2+ (N &0x1); N >>=1; }returnResult }};intMain () {solution S;cout<<s.reversebits (43261596) <<endl;return 0;}
Solving Ideas 2
uint32_t the length of the machine on the basis of idea 1
Implementation Code 2
//runtime:9 ms # Include <iostream> #include "Inttypes.h" using namespace STD ; class Solution {public : uint32_t reversebits (uint32_t N) {uint32_t result = 0 ; uint32_t i; for (i = 1 ; I! = 0 ; I <<= 1 ) {result <<= 1 ; Result |= (N & 0x1 ); n >>= 1 ; } return result; }};
Solving Ideas 3
Solve problems by exchanging bits of unsigned integer numbers directly
Implementation Code 3
//runtime:10 MsclassSolution { Public: uint32_t reversebits (uint32_t N) {uint32_t i; uint32_t x =sizeof(x) *8;//uint32_t number of digits for(i =0; I < x/2; i++) {swapbit (n, I, X-i-1); }returnN }voidSwapbit (uint32_t& N, uint32_t I, uint32_t j) {uint32_t lo = (n >> i) &0x1; uint32_t hi = (n >> j) &0x1;if(lo ^ hi)//I and J-bits are not equal{//0 ^ 1 = 1 //1 ^ 1 = 0 for Exchange purposesN ^= ((1U<< i) | (1U<< j)); } }};
[Leetcode] Reverse Bits