Java solutuon with precalculation of all possible answers


  • 1
    M
    public class Solution {
        public static Map<Integer, Integer> cash = new HashMap<Integer, Integer>();
        public static int reverse16(int n) {
            int reverse = 0;
            for(int i = 0; i < 16; i++ ) {
                reverse = reverse << 1 | (n & 1);
                n >>>= 1;
            }
            return reverse;
        }
        static {
            for(int i = 0; i < 1 << 16; i++) cash.put(i, reverse16(i));
        }
        
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
           return cash.get(n >>> 16) + (cash.get(n & 0XFFFF) << 16);
        }
    }

Log in to reply
 

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