跳至主要內容

9. 回文数


9. 回文数open in new window

🟢   🔖  数学  🔗 力扣open 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回文链表open in new window[✓] 递归 链表 1+
2217找到指定长度的回文数open in new window数组 数学
2396严格回文的数字open in new window脑筋急转弯 数学 双指针
2843统计对称整数的数目open in new window数学 枚举
3260找出最大的 N 位 K 回文数open in new window贪心 数学 字符串 2+
3272统计好整数的数目open in new window哈希表 数学 组合数学 1+