Python solutions with bin() or bit operators


  • 0
    T

    Solve as a string with bin()

    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            res=bin(n).replace('0b','')
            res='0'*(32-len(res))+res
            res=res[::-1]
            return int(res,2)
    

    Solve with bit operators

    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            res=0
            for i in range(32):
                res+=(n>>i&1)<<(31-i)
            return res
    

  • 1
    C

    For your first solution:

    res='0'*(32-len(n))+n
    

    might be corrected as:

    res='0'*(32-len(res))+res
    

  • 0
    T

    @chunyang3 good catch! Sorry for paste the wrong one :p


Log in to reply
 

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