Friday, March 20, 2015

Leetcode - Reverse Bits

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        rs = 0
        # rs = n%2
        # n = n >> 1
        for i in range(32):
            if (n % 2):
                rs = rs << 1
                rs = rs + 1

            else:  
                rs = rs << 1
            n = n >> 1
         
        return rs

Mistake I have made:
1.  It should move the step first and then add one.
                rs = rs << 1
                rs = rs + 1

2. rs has to be initialized before used
                rs = 0 

The cost for this method is very small!!

No comments:

Post a Comment