LeetCode 解题报告 - 9. Palindrome Number

编程语言是 Java,代码托管在我的 GitHub 上,包括测试用例。欢迎各种批评指正!

<br />

题目 —— Palindrome Number

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.

<br >

解答

  • 题目大意
    判断一个整数是否是回文数,不使用额外的存储空间。

    一些提示:
    负数可能是回文数吗?
    如果你考虑把整数转换为字符串,注意题目中要求不使用额外空间。
    你也可以尝试反转这个整数。然而,如果你解决了问题 "Reverse Integer",就会知道反转整数可能会造成溢出。如何解决这个问题?

  • 解题思路

    • 根据提示,采用 "Reverse Integer" 思路,但反转整个数可能会引起溢出,所以我们反转一半,利用回文数左右对称的特性。
    • 负数不可能是回文数,10 的倍数需要单独处理,因为反转时开头的数字为 0。
  • 代码实现

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0 || x != 0 && x % 10 == 0) {
            return false;
        }
        int reverse = 0;
        while (reverse < x) {
            reverse = reverse * 10 + x % 10;
            x = x / 10;
        }
        return (x == reverse) || (x == reverse/10);
    }
}
  • 小结
    联想到利用回文数对称的特性,反转一半的数字,有一点难度。注意整数可能是奇数位或者偶数位,所以 x 和 reverse 的大小需要再判断。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容