From e7d27d936d116acf9f39bc396b5eba0c83faad3a Mon Sep 17 00:00:00 2001 From: = <--gbloal> Date: Sat, 1 Jun 2024 10:25:16 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=9B=9E=E6=96=87=E6=95=B0(9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- leetcode/简单/回文字数.js | 60 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 leetcode/简单/回文字数.js diff --git a/leetcode/简单/回文字数.js b/leetcode/简单/回文字数.js new file mode 100644 index 0000000..6168503 --- /dev/null +++ b/leetcode/简单/回文字数.js @@ -0,0 +1,60 @@ +/* +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));