Solution by coderGirl


  • 0
    C

    Approach #1 Brute Force [Accepted]

    Algorithm

    Handle negative number and overflow separately like in reverse Integer problem

    Java

    public class Solution {
        public boolean isPalindrome(int x) {
            int sign=1;
            if(x<0) {
                sign = -1;
                Math.abs(x);
            }
            int newResult=0,result=0;
            int temp=x;
            while (temp>0)
            {
                int a=temp%10;
                newResult=result*10+a;
                if((newResult-a)/10!=result)
                    return false;
                result=newResult;
                temp=temp/10;
            }
            if(newResult==x)
                return true;
            else
                return false;
        }
    }
    

    Complexity Analysis

    • Time complexity : O(n).

    • Space complexity : O(1)


    Approach #2 Reverse half of the digits [Accepted]

    Thanks to #cbmbbz for the idea

    Algorithm

    No need to write code separately for checking overflow. In this code we check till half of the length.

    Java

    public class Solution {
    public boolean isPalindrome(int x) {
        if(x<0 || (x%10==0 && x!=0))
             return false;
         int rev=0;
         while (x>rev)
         {
             rev=rev*10+x%10;
             x=x/10;
         }
         return (x==rev)||(x==rev/10);
     }
    }
    

    Complexity Analysis

    • Time complexity : O(lgn)

    • Space complexity : O(1)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.