# 毎日一题 - 9. Palindrome number

## 信息卡片

- 时间：2019-07-25
- 题目链接：https://leetcode.com/problems/palindrome-number/submissions/
- tag：`Math`

## 题目描述

```
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.

Follow up:

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

## 参考答案

转成字符串方式
1. 负数都是非回文数，10的整数倍不是回文。
2. 将数字转为字符串，再逆序排列字符串。两者比较，相等就是回文数。

直接操作整数方式
1. 复制x到temp;
2. 取temp末尾数字，方式为temp与10的求余；组成新数reverse;
3. 每取完一位,temp缩小10倍并且去掉小数。
4. reverse要`先扩大十倍`再加上取下来的数
5. 当temp === 0时，表示已经取完；reverse与x比较


参考JavaScript代码：

```js
/**
 * @param {number} x
 * @return {boolean}
 * 转成字符串
 */
var isPalindrome = function(x) {
    if(x < 0 ) return false;
    if(x === 0) return true;
    if(x % 10 === 0) return false;
    let reverse = '';
    let str = String(x);
    for(let i = str.length - 1; i >= 0; i--) {
      reverse += str[i]
    }
    return str === reverse
};

/**
 * @param {number} x
 * @return {boolean}
 * 不转成字符串
 */
var isPalindrome = function(x) {
    if(x < 0 ) return false;
    if(x === 0) return true;
    if(x % 10 === 0) return false;
    let temp = x;
    let reverse = 0;
    while(temp > 0) {
      let num = temp % 10;
      temp = (temp - num)/10; // 或 temp = (temp / 10) >> 0,去除小数位
      reverse = reverse * 10 + num
    }
    return x === reverse
};
```

## 优秀解答

> 暂缺
