Python solution without reversing the number


  • 4
    Y
    from math import log10    
    
    def isPalindrome(self, x):
        if x < 0:
            return False
        if x == 0:
            return True
    
        order = int(log10(x))
        while order >= 0:
            last = x % 10
            x -= last * (10 ** order)
            x /= 10
            order -= 2
        return x == 0
    

    @giacomo. Not exactly. For Python, using library functions is better than writing it by yourself. (Some library functions are actually written in C)

    def test1(x):
        y = x
        order = 0
        while y:
            y //= 10
            order += 1
        return order
    
    
    def test2(x):
        return int(log10(x))
    
    In[49]: timeit -r5 -n10000 test1(8)
    10000 loops, best of 5: 229 ns per loop
    In[50]: timeit -r5 -n10000 test1(256)
    10000 loops, best of 5: 411 ns per loop
    In[51]: timeit -r5 -n10000 test1(4096)
    10000 loops, best of 5: 508 ns per loop
    In[52]: timeit -r5 -n10000 test2(8)
    10000 loops, best of 5: 274 ns per loop
    In[53]: timeit -r5 -n10000 test2(256)
    10000 loops, best of 5: 278 ns per loop
    In[54]: timeit -r5 -n10000 test2(4096)
    10000 loops, best of 5: 298 ns per loop

  • 2
    G

    Instead of calling log10 (which is slow, requires floating point arithmetic and so on...), you can use:

    y = x
    order = 0
    while y:
        y //= 10
        order += 1

  • 0
    Y

    Not exactly. For Python, using library functions is better than writing it by yourself. (Some library functions are actually written in C)


Log in to reply
 

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