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

解题思路:

看到Palindrome就首先想到回文的性质也即定义:关于中心对称。

若数字由奇数个数字组成,则关于中心数字对称; 若数字由偶数个数字组成,则关于中间的(虚拟的)轴对称。

想到几种特殊情况:

  1. x = 0 时,x为回文

  2. x < 0 时,x一定不为回文

首先想到的方法是:将x的最低位取出放到新的数字y里,但是这样有一个风险:x反过来的数字y可能会出现溢出。

这时我们应该利用回文的性质,不需要全部反过来,只反一半:

  若x由偶数个数字组成,那么x与y相等则为回文

  若x由奇数个数字组成,根据我们的判定条件:y去掉最后一位与x相等则为回文

代码:

class Solution {
public:
    bool isPalindrome(int x) {
        if(x == 0){
            return true;
        }
        if(x % 10 == 0){
            return false;
        }
        int y = 0;
        //get the last digit of x and put it into y
        while(x > y){
            y = y*10 + x % 10;
            x /= 10; 
        }
        //check in even digits or odd digits.
        return (x == y) || (x == y/10);
    }
};
原文地址:https://www.cnblogs.com/yaoyudadudu/p/11263303.html