LeetCode(9)——回文数

版权声明:ssupdding https://blog.csdn.net/sspudding/article/details/89243237

一、题目

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

  • 示例 1:
输入: 121
输出: true
  • 示例2
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
  • 示例3
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

思路及代码

  • 思路一:
    如果数字小于0,返回false
    如果等于0,返回true
    如果大于0,,将数字逆序,判断和原数字是否相等,如果相等则返回true,反之
class Solution {

    public boolean isPalindrome(int x) {
        int rev = 0;
        if (x < 0) {
            return false;
        } else if (x == 0) {
            return true;
        } else {
            int num = x;
            while (num != 0) {
                int a = num % 10;
                rev = rev * 10 + a;
                num = num/10;
            }
            if (rev == x) {
                return true;
            }
        }
        return false;
    }
}
  • 思路二:
    如果大于0时,只反转int类型数字的一半,如果该数字是回文,其后半部分反转后应该与原始数字的前半部分相同。
class Solution {

    public boolean isPalindrome(int x) {
       
        // 当 x < 0 时,x 不是回文数
        // 如果数字的最后一位是 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;
    }
}

猜你喜欢

转载自blog.csdn.net/sspudding/article/details/89243237