Python without converting to string


  • 0
    J
    def reverse_integer(x):
        s,l = abs(x),len(str(abs(x)))
        n = 0
        while s:
            t = len(str(s))-1
            d,s = s/(10**t),s%(10**t)
            n += d*10**(l-t-1)
        return cmp(x,0)*n*(n<2**31)
    

  • 0
    J

    Or use divmod,

    def reverse_integer(x):
        s,l = abs(x),len(str(abs(x)))
        n = 0
        while s:
            t = len(str(s))-1
            d,s = divmod(s,10**t)
            n += d*10**(l-t-1)
        return cmp(x,0)*n*(n<2**31) 
    

Log in to reply
 

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