How do I check if a number is a palindrome?

2019-01-02 16:35发布

How do I check if a number is a palindrome?

Any language. Any algorithm. (except the algorithm of making the number a string and then reversing the string).

30条回答
其实,你不懂
2楼-- · 2019-01-02 17:17

A lot of the solutions posted here reverses the integer and stores it in a variable which uses extra space which is O(n), but here is a solution with O(1) space.

def isPalindrome(num):
    if num < 0:
        return False
    if num == 0:
        return True
    from math import log10
    length = int(log10(num))
    while length > 0:
        right = num % 10
        left = num / 10**length
        if right != left:
            return False
        num %= 10**length
        num /= 10
        length -= 2
    return True
查看更多
旧时光的记忆
3楼-- · 2019-01-02 17:19

This is one of the Project Euler problems. When I solved it in Haskell I did exactly what you suggest, convert the number to a String. It's then trivial to check that the string is a pallindrome. If it performs well enough, then why bother making it more complex? Being a pallindrome is a lexical property rather than a mathematical one.

查看更多
春风洒进眼中
4楼-- · 2019-01-02 17:19
def ReverseNumber(n, partial=0):
    if n == 0:
        return partial
    return ReverseNumber(n // 10, partial * 10 + n % 10)

trial = 123454321    
if ReverseNumber(trial) == trial:
    print("It's a Palindrome!")

Works for integers only. It's unclear from the problem statement if floating point numbers or leading zeros need to be considered.

查看更多
裙下三千臣
5楼-- · 2019-01-02 17:19

Push each individual digit onto a stack, then pop them off. If it's the same forwards and back, it's a palindrome.

查看更多
回忆,回不去的记忆
6楼-- · 2019-01-02 17:21

Recursive way, not very efficient, just provide an option

(Python code)

def isPalindrome(num):
    size = len(str(num))
    demoninator = 10**(size-1)
    return isPalindromeHelper(num, size, demoninator)

def isPalindromeHelper(num, size, demoninator):
    """wrapper function, used in recursive"""
    if size <=1:
        return True
    else:       
        if num/demoninator != num%10:
            return False
        # shrink the size, num and denominator
        num %= demoninator
        num /= 10
        size -= 2
        demoninator /=100
        return isPalindromeHelper(num, size, demoninator) 
查看更多
回忆,回不去的记忆
7楼-- · 2019-01-02 17:22

Here is a solution usings lists as stacks in python :

def isPalindromicNum(n):
    """
        is 'n' a palindromic number?
    """
    ns = list(str(n))
    for n in ns:
        if n != ns.pop():
            return False
    return True

popping the stack only considers the rightmost side of the number for comparison and it fails fast to reduce checks

查看更多
登录 后发表回答