Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
If this function is called many times, how would you optimize it?
My solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
uint32_t reverseBits(uint32_t _n) { | |
int p0=0; | |
int p1=31; | |
uint32_t n = _n; | |
while(p0<=p1){ | |
int b0 = n>>p0 & 1; | |
int b1 = n>>p1 & 1; | |
if(b0==1) | |
n = n | b0<<p1; | |
else | |
n = n & ~(1<<p1); | |
if(b1==1) | |
n = n | b1<<p0; | |
else | |
n = n & ~(1<<p0); | |
p0++; | |
p1--; | |
} | |
return n; | |
} | |
}; |
A cool solution using divide and conquer you should not miss!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
uint32_t reverseBits(uint32_t n) { | |
n = (n >> 16) | (n << 16); | |
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8); | |
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4); | |
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2); | |
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1); | |
return n; | |
} | |
}; |
Another solution you have to know !
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uint32_t reverseBits(uint32_t n) { | |
uint32_t m = 0; | |
for (int i = 0; i < 32; i++, n >>= 1) { | |
m <<= 1; | |
m |= n & 1; | |
} | |
return m; | |
} |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
uint32_t reverseBits(uint32_t n) { | |
for(int i=0; i<=15; i++){ | |
int p0 = i; | |
int p1 = 31-i; | |
if(((n>>p0)&1)^((n>>p1)&1)){ | |
n = (1<<p0)^n; | |
n = (1<<p1)^n; | |
} | |
} | |
return n; | |
} | |
}; |
No comments:
Post a Comment