# Palindrome Number

leetcode 专栏收录该内容
6 篇文章 0 订阅

## 一 问题描述

### Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
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.


Coud you solve it without converting the integer to a string?

## 二 解法

### 1. 第一解法（个人，转换字符串）

var isPalindrome = function(x) {

let str = x.toString().split("");

let len = str.length - 1;
let mid = str.length / 2;

for (let i = 0; i <= mid; i++) {
if (str[i] !== str[len - i])
return false
}
return true;
};


### 2. 第二解法（个人，非转字符串）

var isPalindrome = function(x) {

let num = x;
let arc = 0;

if (x < 0)
return false;

while (num >= 10) {
arc *= 10;
arc += num % 10;
num = Math.floor(num /10);
}

arc = arc * 10 + num;
return arc === x;

};


### 3. 第三解法（个人，最优，非转字符串）

1. 是否相等，如果相等， 必定是回文串
2. 前半段此时已经小于后半段，说明，如果前半段乘10加上后半段的个位数如果和后半段相等，也可以判定为回文串。

    var isPalindrome = function(x) {

let num = x;
let arc = 0;

if (x < 0 || x % 10 === 0 && x !== 0)
return false;

while (num > arc) {
arc *= 10;
arc += num % 10;
num = Math.floor(num /10);
}

if(arc === num || num * 10 + arc % 10 === arc)
return true;

return false;
};


11509 / 11509 test cases passed.
Status: Accepted
Runtime: 164 ms
Memory Usage: 45.3 MB
Runtime：faster than 98%


By DoubleJan
2019.7.7

• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

07-31 624

10-10 1132
08-30 638
05-31 160
08-03 1159
08-26 1026
06-03 420
09-05 37
05-28 498
07-21 1097