Leetcode – 9 – Palindrome Number

Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

Description:

In this problem we have to check if the integer is a palindrome or not. for eg. 123454321 is a palindrome.

Brute Force Solution: (convert the integer to string and find the reverse of it)

This is very first brute force approach for this problem. We convert the given integer to a string and then find the reverse of the string and then compare it with the original string.

This approach is good but we have to complexity of time and space to convert the integer to a string and reverse it.

Efficient solution: (Using Modulo)

The efficient solution can be find the modulo and store it in a variable and finally check with the original number. This will identify if the number is same as the reverse of it.

1

Code:

public class Solution {
    public boolean isPalindrome(int x) {
             int n = x;
             int result=0;
             while(n > 0){
                 result = result*10 + n%10;
                 n = n/10;
             }
             if(result == x){
                 return true;
             }    

         return false;       
    }
}

Time Complexity: O(n)

  • Loop through the digits upto n – O(n)

Space Complexity: O(1)

  • We will store the values in the result – O(1)

Available Test Cases: 11506

  • handle overflow cases

 Github:

Leetcode_9_Palindrome_Number

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: