algorighm/leetcode/简单/回文字数.js
2024-06-01 10:28:44 +08:00

61 lines
1.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
9. 回文数
已解答
简单
相关标签
相关企业
提示
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数
是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如121 是回文,而 123 不是。
示例 1
输入x = 121
输出true
示例 2
输入x = -121
输出false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3
输入x = 10
输出false
解释:从右向左读, 为 01 。因此它不是一个回文数。
提示:
-231 <= x <= 231 - 1
进阶:你能不将整数转为字符串来解决这个问题吗?
*/
/*
思路:由于是数字,我们不能像处理字符串那样使用双指针处理,当然你也可以把数字转换成字符串
再进行处理,可是这不在我们讨论的范围。我们依次取出末尾的数字,把它拼接成一个新的数字,如果
数字是回文数,那么拼接的新数字会和它相等,具体看代码
*
/
/**
* @param {number} x
* @return {boolean}
*/
const isPalindrome = function (x) {
if (x < 0 || (x % 10 === 0 && x !== 0)) return false;
let revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = (revertedNumber * 10) + (x % 10);
x = Math.floor(x / 10);
}
// 当数字为奇数位时revertedNumber会大于x只要/10之后任然相等那么就是回问数
return revertedNumber === x || Math.floor(revertedNumber / 10) === x;
};
console.log(isPalindrome(1221));