Using C++ , without extra space , digit compare


  • 1
    Z
    int piece(int x,int index){
        return int(x/pow(10,index-1))%10;
    }
    
    bool isPalindrome(int x) {
        if(x<0)return false;
        int len = log(x)/log(10)+1;
        for(int i=1;i<=len/2;i++){
            if(piece(x,i)!=piece(x,len+1-i))return false;
        }
        return true;
    }

  • 0
    G

    if input == 1,log(x) will overflow.
    you may add one line : if(x == 0) return 1;
    after if(x<0)return false;


  • 0
    Z

    Yes , u are right !

    If input == 0,log(x) will overflow. you may add one line : if(x == 0) return 1; after if(x<0)return false;

    thanks for your advise!


Log in to reply
 

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