An O(log(n)) solution without math library. (no overflow)


  • -1
    J
    class Solution {
    public:
        bool isPalindrome(int x) {
            if (x < 0) return false;
            // if x is 121, let d = 100 (a 1 followed by length(x)-1 zeros)
            int d = 1;
            for (int y = x; y >= 10; y /= 10) d *= 10;
            while (d != 0 && x != 0) {
                if (x / d != x % 10) return false;  // head and tail are unequal
                x = x % d / 10;  // cut the head and tail
                d /= 100;
            }
            return true;
        }
    };

  • 0
    J

    Anyone can tell me why it was downvoted?


Log in to reply
 

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