Leetcode 9 Solution

This article provides solution to leetcode question 9 (palindrome-number)

https://leetcode.com/problems/palindrome-number

Thinking Process

The simplest way would be to compare the string with its reverse.

As for the follow-up question, we can reverse the integer by putting each digits in array, and then popping them back reversely. Then comparing the reversed integer with the original one will give us the result.

Time & Space Complexity

Assuming N is the bit-length of the number.

  • Time complexity: O(N)
  • Space complexity: O(N)

Solution

class Solution {
public:
    int reverse(int x) {
        vector<int> nums;

        int64_t v = x;

        while (v != 0)
        {
            nums.push_back(v % 10);
            v /= 10;
        }

        for (auto it = nums.begin(); it != nums.end(); it++)
        {
            v = v * 10 + *it;
        }

        if (v > INT_MAX)
            return 0;
        else if (v < INT_MIN)
            return 0;
        else
            return v;
    }

    bool isPalindrome(int x) {
        if (x < 0)
            return false;

        return x == reverse(x);
    }
};