Optimized solution for bulk reverse


  • 3
    Y
    class Solution:
        # @param n, an integer
        # @return an integer
        def __init__(self):
            self.m = None
            self._calc_reverse_map()
            
        def _calc_reverse_map(self):
            self.m = [0] * (2 ** 8)
            for i in range(2 ** 8):
                self.m[i] = self._reverse(i) >> 24
    
        def _reverse(self, n):
            res = 0
            for i in range(0, 32):
                if n & (1 << (31 - i)):
                    res |= 1 << i
            return res
    
        def reverseBits(self, n):
            m = self.m
            return m[(n & 0xFF)] << 24 \
                 | m[(n >> 8) & 0xFF] << 16 \
                 | m[(n >> 16) & 0XFF] << 8 \
                 | m[(n >> 24) & 0XFF]

Log in to reply
 

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