topic

Given an integer x, return true if x is a palindrome; otherwise, return false.

A palindrome is an integer that reads the same in positive order (from left to right) and in reverse order (from right to left).

For example, 121 is a palindrome, but 123 is not.

输入:x = 121
输出:true

输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

Convert to string flip

The simplest and least efficient method, because converting numbers into strings requires opening up additional space, which increases space complexity.

def isPalindrome(x: int) -> bool:
        return str(x) == str(x)[::-1]

Reverse numbers using division

Converting to a string takes more space.
Invert the number directly and compare it with the original value.
Some questions explain that considering that the reversed number may overflow, only half of it is reversed. If x is a palindrome, it should be symmetrical.
In fact, if x is a palindrome, the value of x has been determined and it will not overflow, and the inversion of x is itself so it cannot overflow. If x is not a palindrome, it will either not be equal to itself after inversion, or it will overflow.

The principle of digital inversion:

  • x%10, the remainder is the last digit of x
  • x//10, the result is the other digits with the last digit removed
# 不考虑溢出,全部反转
def isPalindrome(x):
    if x < 0 or (x % 10 == 0 and x != 0):
        return False
    originalNum = x
    revertedNum = 0
    while x > 0:
        revertedNum = revertedNum * 10 + x % 10
        x = x // 10
    return revertedNum == originalNum

The principle of inverting half
1221, reverse half of 12, compare with the remaining 12
12321, reverse half of 123, //10 rounded up to 12, compared with the remaining 12
When x> the number of inversions, only one inversion

# 考虑溢出,只反转一半
def isPalindrome(x):
    if x < 0 or (x % 10 == 0 and x != 0):
        return False
    revertedNum = 0
    while x > revertedNum:
        revertedNum = revertedNum * 10 + x % 10
        x = x // 10
    return revertedNum == x or (revertedNum // 10) == x

Ethan
140 声望11 粉丝

水平较低,只是记录,谨慎参阅


引用和评论

0 条评论