跳转至

9.Palindrome Number

Tags: Math Easy

Links: https://leetcode.com/problems/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?


class Solution {
public:
    bool isPalindrome(int x) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (x < 0) return false;

        int base = 1;
        while (x / base >= 10) base *= 10;

        while (x != 0) {
            int right = x % 10;
            int left = x / base;
            if (left != right) return false;
            x = (x % base) / 10; 
            base /= 100; //这里注意
        }

        return true;
    }
};

不断地去验证首位地数字是否相等。

另外一种就是考虑数字折半,考察一半地数字反转过来是否和前半部分相等,需要注意奇数和偶数地不同判断。

class Solution {
public:
    bool isPalindrome(int x) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (x < 0 || (x % 10 == 0 && x != 0)) return false;
        int num = 0;
        while (x > num) {
            num = num * 10 + x % 10;
            x /= 10;
        }

        return (x == num || x == num / 10);
    }
};

最简单直接地思路当然是转成字符串考虑了。

class Solution {
public:
    bool isPalindrome(int x) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (x < 0) return false;

        string s = to_string(x);
        int start = 0, end = s.size() - 1;
        while (start <= end) {
            if (s[start++] == s[end--]) continue;
            else return false;
        }

        return true;
    }
};