Skip to content

Reverse Bits

leetcode

what is wrong with this code?

    int reverseBits(int n) {
        int ans = 0;
        for (int i = 0 ; i < 32; i++) {
            if (n & 1) {
                ans = ans | 1;
            } 
            ans = ans << 1;
            n = n >> 1;
        }
        return ans;
    }

note here, we calculate the value of ans before shifting it to the left. This means that the last bit of ans will always be 0, which is not correct. We should calculate the value of ans after shifting it to the left.

    int reverseBits(int n) {
        int ans = 0;
        for (int i = 0 ; i < 32; i++) {
            ans = ans << 1;
            if (n & 1) {
                ans = ans | 1;
            } 
            n = n >> 1;
        }
        return ans;
    }