Reverse Bits
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?
Related problem: Reverse Integer
------------------- thinking ---------------------------------------
https://oj.leetcode.com/discuss/27405/o-1-bit-operation-c-solution-8ms
https://oj.leetcode.com/discuss/27375/my-c-10ms-version
----------------- codes------------------------------------------
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
//int sign_bit = 0;
//if (n < 0) {
// sign_bit = 1;
// n = -n;
//}
uint32_t out = 0;
int cnt = 32;
while (cnt > 0) {
int bit = n % 2;
n = n >> 1;
out = (out << 1) + bit;
cnt--;
}
//return out + sign_bit;
return out;
}
};
No comments:
Post a Comment