9. Palindrome Number

1. Description

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

2. Follow Up

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

3. Example

Example 1:
Input: x = 121
Output: true

Example 2:
Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Example 4:
Input: x = -101
Output: false

4. Constraints

  • $−2^{31}$ <= x <= $2^{31}$ − 1

5. Solutions

My Accepted Solution(Follow Up)

Refer to Leetcode 7

Time complexity: O(1)
Space complexity: O(1)

class Solution {
public:
    bool isPalindrome(const int x) {
        if (x >= 0) {
            long origin = x, reverse = 0;
            while (origin > 0) {
                reverse = reverse * 10 + origin % 10;
                origin /= 10;
            }

            return x == reverse;
        } else {
            return false;
        }
    }
};
Last updated:
Tags: Math
comments powered by Disqus