AC Python 44 ms solution, bit manipulation


  • 7
    def reverseBits(self, n):
        ans = 0
        for i in xrange(32):
            ans = (ans << 1) + (n & 1)
            n >>= 1
        return ans
    
    
    # 600 / 600 test cases passed.
    # Status: Accepted
    # Runtime: 44 ms
    # 98.59%
    

    Just generate the answer bit by bit, do not use things like "% 2" or "2 ** k" or "bin". Bit manipulation is a lot faster. One small thing is the plus operator can be replaced by "bitwise or", aka "|". However i found plus is more readable and fast in python.


  • 0
    G

    Nice solution!


  • 0
    C

    nice work, thanks a lot for reminding me the & in Python!


  • 0
    T

    Beautiful Solution!! Thank you.


  • 0
    S

    that should be a real "algorithmic" soln


Log in to reply
 

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