C++ overflow-free solution by using a mask

  • 4

    The idea is to use a mask integer which is the largest power of 10 that is smaller or equal than x. Then use it as a mask to get the most significant bit (MSD) and compare with the least significant bit (LSD). Next time strip off MSD and LSD and repeat, until the two digits meet.

    class Solution {
        bool isPalindrome(int x) {
            if (x < 0) return false;
            //determine minimum power of 10 smaller or equal than x
            int mask = 1;
            while (x / mask >= 10) mask *= 10; 
            while (mask > 1) {
                if (x / mask != x % 10) return false;
                x = (x % mask) / 10; //strip off first and last digit
                mask /= 100; //update mask
            return true;

  • 0

    Absolutely the best solution I have ever seen. Good job

  • 0

    second time, still the best solution !

Log in to reply

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