跳至主要內容

9. Palindrome Number


9. Palindrome Numberopen in new window

🟢   🔖  数学  🔗 LeetCodeopen in new window

题目

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:

  • -2^31 <= x <= 2^31 - 1

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

题目大意

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

解题思路

判断一个整数是不是回文数,先将整数转换为字符串。

然后用对撞指针分别一前一后开始扫描,如果前后的字段相同,则移动指针,否则直接返回 false

代码

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function (x) {
	x = '' + x;
	let left = 0;
	let right = x.length - 1;
	while (left < right) {
		if (x[left] === x[right]) {
			left++;
			right--;
		} else {
			return false;
		}
	}
	return true;
};

相关题目

相关题目
- [234. 回文链表](./0234.md)
- [2217. 找到指定长度的回文数](https://leetcode.com/problems/find-palindrome-with-fixed-length)
- [2396. 严格回文的数字](https://leetcode.com/problems/strictly-palindromic-number)
- [2843. Count Symmetric Integers](https://leetcode.com/problems/count-symmetric-integers)