Example: Reverse Bits - rFronteddu/general_wiki GitHub Wiki

Reverse bits of a given 32 bits unsigned integer.

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        // for each bit
        int ans = 0;
        for (int i = 0; i < 32; i++) {
            // shift left to make space for new bit
            ans <<= 1;
            // reverse the current bit
            ans |= (n&1); 
            // move to the next input bit
            n >>=1;
        }
        return ans;
    }
}