[LeetCode] 9. Palindrome Number

Given an integer x, return true if x is a palindrome, and false otherwise.

Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints:
-231 <= x <= 231 - 1

Follow up: Could you solve it without converting the integer to a string?

回文数。

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/palindrome-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

题意是判断一个数字是否是回文数。这个题跟第七题非常类似,有两种做法,一种跟第七题很类似,另一种是把 input 数字转换成字符串然后双指针逼近检测是否有不一样的字符。

无论什么做法,都有一些需要去掉的 corner case,首先负数一定不是回文数,能被 10 整除的数字也不是,其次回文数一定不会越界。

复杂度

时间O(n) - input 数字的长度
空间O(1)

代码

Java实现

class Solution {
    public boolean isPalindrome(int x) {
        // corner case
        if (x < 0) {
            return false;
        }

        // normal case
        int n = x;
        int res = 0;
        while (n != 0) {
            res = res * 10 + n % 10;
            if (res > Integer.MAX_VALUE) {
                return false;
            }
            n /= 10;
        }
        return res == x;
    }
}

JavaScript实现

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function (x) {
	// corner case
	if (x < 0 || (x !== 0 && x % 10 === 0)) {
		return false;
	}

	// normal case
	let palindrome = x;
	let reverse = 0;
	while (x > 0) {
		reverse = reverse * 10 + (x % 10);
		x = ~~(x / 10);
	}
	return palindrome === reverse;
};

相关题目

7. Reverse Integer
9. Palindrome Number
posted @ 2020-01-16 13:51  CNoodle  阅读(416)  评论(0编辑  收藏  举报