EchoDemo's Blogs

LeetCode 回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121
输出: true


示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。


示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

题解1(转字符串)

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0)
            return false;
        String str = String.valueOf(x);
        int len = str.length();
        int count = 0;
        for (int i = 0; i < len / 2;i++) {
            if (str.charAt(i) == str.charAt(len -i - 1)) {
                count++;
                continue;
            }
            break;
        }
        return count == (len / 2);
    }
}

执行用时 :13 ms, 在所有 Java 提交中击败了25.05%的用户

内存消耗 :40.5 MB, 在所有 Java 提交中击败了5.00%的用户

题解2(不转字符串,使用栈)

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0)
            return false;
        if (x == 0)
            return true;
        Stack<Integer> s = new Stack<>();
        int i = 0, j =0, y = x;
        while (true) {
            if (x == 0) break;
            s.push(x % 10);
            x /= 10;
            i++;
        }
        while (!s.isEmpty()) {
            if (s.pop() == (y % 10)) {
                j++;
                y /= 10;
                continue;
            }
            break;
        }
        return i == j;
    }
}


执行用时 :22 ms, 在所有 Java 提交中击败了5.05%的用户

内存消耗 :40.2 MB, 在所有 Java 提交中击败了5.00%的用户

题解3(官方题解)

class Solution {
    public boolean isPalindrome(int x) {
        // 特殊情况:
        // 如上所述,当 x < 0 时,x 不是回文数。
        // 同样地,如果数字的最后一位是 0,为了使该数字为回文,
        // 则其第一位数字也应该是 0
        // 只有 0 满足这一属性
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }
        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        // 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
        // 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123,
        // 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。
        return x == revertedNumber || x == revertedNumber/10;
    }
}

执行用时 :9 ms, 在所有 Java 提交中击败了98.74%的用户

内存消耗 :40.2 MB, 在所有 Java 提交中击败了5.00%的用户
🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------