7 line simple C++ solution beats 90% submissions in O(1) space, two pointers


  • 26

    Use two pointers concept, find the half point, and compare first half and 2nd half.

    Variable revhalf is the reversed 2nd half(x has even number of digits), or 2nd half with the middle digit(if x has odd number of digits)

    class Solution {
    public:
        bool isPalindrome(int x) {
            if(x < 0) return false;
            int revhalf = 0, slow = x, fast = x;
            while(fast){ 
                revhalf = revhalf * 10 + slow % 10;
                slow /= 10;
                fast /= 100;
            }
            return slow == revhalf || slow == revhalf / 10;
        }
    };

  • 9
    S

    @Ximin.Z Hi,Ximin.Even though this code can pass all the cases, I think it not correct. Since you didn't consider the numbers which are divisible by 10.
    e.g. 21120 is not a palindrome number,but your program will return true.
    am I right?


  • 0
    X

    @Ximin.Z this code can not pass all the cases,I believe you didn't consider the numbers which can divided by 10.


  • 1
    E

    Your code will fail the test case 21120, just because of the small mistake with handling of odd and even length.

    class Solution {
    public:
        bool isPalindrome(int x) {
            if(x<0) return false;
            int fast=x,slow=x,rhalf=0;
            while(fast/10){
                rhalf = rhalf*10 + slow%10;
                slow /= 10;
                fast /= 100;
            }
            return fast==0?rhalf==slow:slow/10==rhalf;
        }
    };
    

    Just minor fix for that, this will pass all the test cases...
    @Ximin-Z @xueweichengxing @surong


  • 0
    G

    It failed for 12210 (output true, but should be false).
    Line 4 should be changed to be
    if(x < 0 || (x > 0 && x%10==0)) return false;
    Then it will work fine.


Log in to reply
 

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