Java solution w/ lookup table, 3ms


  • 0
    J
    public class Solution {
        // 4-bit lookup table
        int[] lookup = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
        
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int output = 0;
            for (int i=0; i<8; ++i) {
                output <<= 4;
                output |= lookup[n & 0xf];
                n >>= 4;
            }
            return output;
        }
    }
    

    So for instance lookup[3] = 12 because 3 is 0011 and 12 is 1100.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.