Created
July 17, 2016 00:11
-
-
Save jianminchen/3526dd68e72ae97563cdd61580052016 to your computer and use it in GitHub Desktop.
reverse bit 32 unsigned integer - C++ solution provided by facebook code lab
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: | |
unsigned int swapBits(unsigned int x, unsigned int i, unsigned int j) { | |
unsigned int lo = ((x >> i) & 1); | |
unsigned int hi = ((x >> j) & 1); | |
if (lo ^ hi) { | |
x ^= ((1U << i) | (1U << j)); | |
} | |
return x; | |
} | |
unsigned int reverse(unsigned int x) { | |
unsigned int n = sizeof(x) * 8; | |
for (unsigned int i = 0; i < n/2; i++) { | |
x = swapBits(x, i, n-i-1); | |
} | |
return x; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment