LeetCode Palindrome Number

 Problem Description Link: https://leetcode.com/problems/palindrome-number/


Accepted Solution

/*

The solution is easy, and I believe everyone knows the process. However, one problem is that x is a number. If it is a string, in that case, we can get the result after reversing it. Therefore, to solve the problem, we have to find the digits by modulating 10, store them in an array, and finally compare from both sides. If we find any discrepancy, we can tell it is not a palindrome. Note that any negative integer would never be a palindrome since it should contain a minus (-) sign.

*/


class Solution {
public:
    bool isPalindrome(int x) {
        int digit[50], len=0;
        bool f = true;

        if(x < 0) {
            return false;
        }

        while(x>0)
        {
            digit[len++] = x%10;
            x/=10;
        }

        for(int i=0, j=len-1; i<len; i++, j--)
        {
            if(digit[i] != digit[j])
            {
                f = false;
                break;
            }
        }

        return f;
    }
};

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld