Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 17, 2016 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/3526dd68e72ae97563cdd61580052016 to your computer and use it in GitHub Desktop.
Save jianminchen/3526dd68e72ae97563cdd61580052016 to your computer and use it in GitHub Desktop.
reverse bit 32 unsigned integer - C++ solution provided by facebook code lab
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