Directly Comparing Each Digit, No Overflow Risk (C++)


  • 1
    F
    class Solution {
    public:
        bool isPalindrome(int x) {
            if(x < 0) return false;
    
            int size = log10(x);
            while(size > 0){
                if(x%10 != (int)(x/pow(10, size))%10)  return false;
                x/=10;                
                size-=2;
            }        
            return true;
        }
    };
    

  • 0
    B

    Could you explain more about using "log10(x)" and "x / pow(10, size) % 10"?


  • 1
    F

    Sure thing. The log10 gets me the total number of digits in a number, minus 1. So, log10(101) = 2, log10(1001) = 3, and so on.

    Once I know the total size, in digits, of the number, it is a matter of extracting out the numbers I care to compare on each iteration. That is where the pow comes in. It lets me divide the number so that the most significant digit I wish to compare is now in the ones spot, so modulo 10 of that will give me the most number I want to check against on each loop. I think an example is easier to follow.

    Lets say the number we want to check is 12321. In this case, int size = 4 (log10(12321) as an integer is rounded to 4)

    now we loop while size > 0
    Iteration 1:
    x%10 = 1
    x/pow(10, size) = 12321/10^4 = 12321/10000 = 1
    1%10 = 1, so 1==1, keep looping.
    x = x/10 = 12321/10 = 1232
    size -=2 = size = 2

    Iteration 2:
    x%10 = 2
    x/pow(10, size) = 1232/10^2 = 1232/100 = 12
    12%10 = 2, so, 2 == 2, keep looping
    x = x/10 = 1232/10 = 123
    size-=2 = size = 0

    Since size == 0, we stop the loop knowing it is a palindrome

    If this doesn't make sense ping me again and I can try to explain it better.


  • 0
    B
    This post is deleted!

  • 0
    B

    @frenchtoast6369

    Thank you very much for your illuminating explanation!

    Now I understand it.This is concise and smart. It is great to know about this new solution! : )


Log in to reply
 

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