Thursday, August 20, 2015

Reverse Bits | Leetcode

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

---

Solution: As in any reverse operation, start iterating from the start and the end. It does not matter if you start iterating from the middle or from the two ends. Swap the current first and last bits. The code for bit swap looks different from that of swapping two variables. We use "(n >> i) & 1" to extract a bit's value at position i. Then we use "n ^= (1 << i)" to toggle the bit's value at position i.
public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int first = 0;
        int last = 31;
        do {
            int firstBit = (n >> first) & 1;
            int lastBit = (n >> last) & 1;
            if (firstBit != lastBit) {
                n ^= (1 << first) | (1 << last);
            }
            first++;
            last--;
        } while (first < last);
        return n;
    }
}

No comments: