C++ code beats 100% submissions


  • -1
    H
    class Solution {
    public:
        bool isPalindrome(int x) {
            if (x < 0) return false;
            
            int length = 0;
            int copy = x;
            while (copy != 0) {
                copy /= 10;
                length++;
            }
            
            int half_l = length / 2;
            for (int i = 0; i < half_l; ++i) {
                if (!(getDigit(x, i) == getDigit(x, length - 1 - i))) return false;
            }
            return true;
        }
        
        const int getDigit(const int x, int rpos) {
            int c1 = x;
            int c2 = x;
            
            c1 /= pow(10, rpos);
            c2 /= pow(10, rpos + 1);
            return c1 - 10 * c2;
        }
    };
    

  • 0
    H

    The previous one seems straight forward but somewhat silly.

    Check out this new one:

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

Log in to reply
 

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