[Easy] 9. Palindrome Number

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.
Follow up:

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

Solution

class Solution {
public:
    bool isPalindrome(int x) {
        int val = 0;
        int origin = x;
        if (x < 0) return false;
        while( x != 0)
        {
            int pop = x % 10;
            x /= 10;
            if ( val > INT_MAX/10 || (val == INT_MAX/10 && pop > 7)) return false;
            val = val * 10 + pop;
        }
        if (val == origin) return true;
        else return false;
    }
};

解题思路

先把整型数反转,在不溢出的情况下判断回文与原文是否相等。

发布了85 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lun55423/article/details/105545737