leetcode 9 Palindrome Number 回文数

简介: Determine whether an integer is a palindrome. Do this without extra space.click to show spoilers.

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:
Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

非常简洁的c++解决方案:
对于回文数只比较一半

public boolean isPalindrome1(int x) {
    if (x == 0) return true;
    // in leetcode, negative numbers and numbers with ending zeros
    // are not palindrome
    if (x < 0 || x % 10 == 0)
        return false;

    // reverse half of the number
    // the exit condition is y >= x
    // so that overflow is avoided.
    int y = 0;
    while (y < x) {
        y = y * 10 + (x % 10);
        if (x == y)  // to check numbers with odd digits
            return true;
        x /= 10;
    }
    return x == y; // to check numbers with even digits
}

python这个解法应该是前后分别对比:


class Solution:
    # @param x, an integer
    # @return a boolean
    def isPalindrome(self, x):
        if x < 0:
            return False

        ranger = 1
        while x / ranger >= 10:
            ranger *= 10

        while x:
            left = x / ranger
            right = x % 10
            if left != right:
                return False

            x = (x % ranger) / 10
            ranger /= 100

        return True

python字符串的解法:

class Solution:
    # @param {integer} x
    # @return {boolean}
    def isPalindrome(self, x):
        return str(x)==str(x)[::-1]
相关文章
|
2月前
|
算法 Java
[Java·算法·简单] LeetCode 9. 回文数 详细解读
[Java·算法·简单] LeetCode 9. 回文数 详细解读
57 0
|
2月前
|
Go
golang力扣leetcode 479.最大回文数乘积
golang力扣leetcode 479.最大回文数乘积
28 0
|
1月前
|
存储 SQL 算法
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode 题目 65:有效数字(Valid Number)【python】
|
2月前
leetcode代码记录(回文数
leetcode代码记录(回文数
24 1
|
2月前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
21 0
|
2月前
【力扣】9. 回文数
【力扣】9. 回文数
|
2月前
|
算法 Java
[Java·算法·简单] LeetCode 9. 回文数 详细解读
[Java·算法·简单] LeetCode 9. 回文数 详细解读
29 0
|
2月前
|
算法 Java
|
2月前
leetcode-9:回文数
leetcode-9:回文数
26 0
|
8月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
78 1