[LeetCode] 9. Palindrome Number

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 9. Palindrome Number相关的知识,希望对你有一定的参考价值。

回文数。题意是判断一个数字是否是回文数。这个题跟第7题非常类似,几乎是一样的做法。例子,

Example 1:

Input: 121
Output: true

Example 2:

Input: -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: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

首先负数一定不是回文数,其次回文数一定不会越界所以少一些判断。代码如下,

时间O(n)

空间O(1)

 1 /**
 2  * @param {number} x
 3  * @return {boolean}
 4  */
 5 var isPalindrome = function(x) {
 6     // corner case
 7     if (x < 0 || (x !== 0 && x % 10 === 0)) return false;
 8 
 9     // normal case
10     let palindrome = x;
11     let reverse = 0;
12     while (x > 0) {
13         reverse = reverse * 10 + (x % 10);
14         x = ~~(x / 10);
15     }
16     return palindrome === reverse;
17 };

以上是关于[LeetCode] 9. Palindrome Number的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 9. Palindrome Number

LeetCode - 9 - Palindrome Number

Leetcode:9- Palindrome Number

LeetCode_9. Palindrome Number

leetcode-9 Palindrome Number

Leetcode 9. Palindrome Number