Palindrome number - Leetcode

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.

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0)
        {
            return false;
        }
        else
        {
            int n=x,m,a=0;
            while(n>0)
            {
                m=n%10;
                a=a*10+m;
                n/=10;
            }
            if(a==x)
                return true;
            else
                return false;
               
        }
       
    }
}


Click this link to try it on Leetcode

Here, if the number is less than 0 (i.e. negative value) that number must not be a palindrome. So we can ignore that case. For positive number we have to check for palindrome.

1) We have to get each digit by using modulus operator.
2)Multiply with 10 for each digit so that it can form a number equal to given number and add it as sum.
3)Get quotient of number and repeat step 1, 2 until  number is equal to 0.

For more Leetcode Problems

Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II