Missing TC


  • 0

    My solution is to remove the leftmost digit and rightmost digit per recursion.

    But i missed the '0's between each recursion.

    For example, 10022201, after first recursion, it becomes 222, and returns true, but should be false. but the solution still get accepted.

    Code:

    class Solution {
    public:
        bool isPalindrome(int x) {
            if(x < 0) return false;
            if(x < 10) return true;
            int base = 0;
            int t = x;
            while(t/10){
                t /= 10;
                base++;
            }
            if(t != x%10) return false;
            int n = (x - t*pow(10, base))/10;
            if(n == 0) return true;
            if(n < pow(10, (base - 1)/2)) return false;
            while(n%10 == 0) n /= 10;
            return isPalindrome(n);
        }
    };
    

    A way to correct my solution is to count the '0's in 'left' and 'right', but will be too complicated and I feel that's not a solution should be...


    Just for clear up, a clever idea from this post, and my C++ version.

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

Log in to reply
 

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