跳至主要內容

9. 回文数


9. 回文数

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