Palindrome Number

本贴最后更新于 2254 天前,其中的信息可能已经时移世易

题目描述

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

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.

判断数字是不是回文数字。

解题思路

不能用额外的空间,所以不能用字符串或数组。

可以用一个 long 去计算翻转后的数字是否和原数字相等。

  • 负数全部是 false;
  • 超出范围是 false;
  • 不相等是 false;
  • 相等时 true。

代码

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0)
            return false;
        long ret = 0;
        int tmp = x;
        do {
            ret *= 10;
            ret = ret + x % 10;
            x /= 10;
            if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE)
                return false;
        } while (x != 0);
        return tmp == ret;
    }
}
  • 算法
    388 引用 • 254 回帖 • 22 关注
  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    209 引用 • 72 回帖 • 3 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...