首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode 9 Palindrome Number 回文数

leetcode 9 Palindrome Number 回文数

作者头像
流川疯
发布2019-01-18 15:24:08
4190
发布2019-01-18 15:24:08
举报

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]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年06月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档