Leet Code 9. Palindrome Number

题目
Determine whether an integer is a palindrome. Do this without extra space.

Some hints: Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

翻译
判断一个int整数是否是自己的迴文数,不能使用额外的空间来操作。

提示:
负整数会是自己的迴文数吗(ex. -1)

如果你想用字串来解是不行的,因为不能使用额外的空间。

你也可以反转整数,如果你之前已经做过LeetCode 7. Reverse Integer,你会知道反转后的数可能会超过integer的最大值。

範例1
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

範例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.

解题

/** * @param {number} x * @return {boolean} */var isPalindrome = function(x) {    var reverse = 0;    var copy = x;    while (copy > 0) {      const digit = copy % 10;       //i=1 => 1141 % 10 = 1 | i=2 => 114 % 10 = 4 | i=3 => 11 % 10 = 1 | i=4 => 1 % 10 = 1      reverse = reverse * 10 + digit;       // i=1 => 0 * 10 + 1 = 1 | i=2 => 1 * 10 + 4 = 14 | i=3 => 14 * 10 + 1 = 141 | i=4 => 141 * 10 + 1 = 1411      copy = Math.floor(copy / 10);       // i=1 => 1141/10 = 114 | i=2 => 114/10 = 11 | i=3 => 11/10 = 1 | i=4 => 1/10 = 0    }    return reverse === x;};

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章