LeetCode 解题报告 - 9. Palindrome Number

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


题目 —— 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.


解答

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

    一些提示:
    负数可能是回文数吗?
    如果你考虑把整数转换为字符串,注意题目中要求不使用额外空间。
    你也可以尝试反转这个整数。然而,如果你解决了问题 "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 的大小需要再判断。

你可能感兴趣的:(LeetCode 解题报告 - 9. Palindrome Number)