My Python code without using bin function 60 ms


  • 0
    F
    class Solution(object):
    def reverseBits(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = []
        for i in xrange(32):
        	if (n>>(i+1)) == 0:
        	    if n>>i == 0:
        	        res.append(0)
        	    else:
        	        res.append(1)
        	elif (n>>i) / (n>>(i+1)) == 2 and (n>>i) % (n>>(i+1)) == 0:
        		res.append(0)
        	else:
        		res.append(1)
        return reduce(lambda x, y: x*2 + y, res)
    

    I've always thought it is kind of cheating to use bin() in such questions so I come up with this. Not sure if it can be improved?


Log in to reply
 

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