Fails on case #1030, not sure why


  • 0
    N

    Can someone explain why this case fails? I'm new to this kind of programming. It must be int overflow, but the output is still positive, whereas I thought overflow should make the number negative?
    Here is the output:

    Input:	1534236469
    Output:	1056389759
    Expected:	0
    

    Thanks

    class Solution {
    public:
        int reverse(int x) {
            bool isNegative = false;
            if (x < 0)
            {
                isNegative = true;
                x *= -1;
            }
            
            int reversed = 0;
            while (x > 0)
            {
                int digit = x % 10;
                reversed *= 10;
                reversed += digit;
                x /= 10;
                
                if (isNegative == false && reversed < 0)
                    return 0;
            }
            
            if (isNegative == true)
                reversed *= -1;
                
            return reversed;
        }
    };

  • 0
    U

    Because the reverse number is greater than the largest number int can hold. In that case, you return 0


  • 1
    I

    Hi,
    I used long for the reverse number not an int and tested

    if (reverse>INT_MAX) return 0; after the while loop;

    I think this should help. The problem in you code is that at some point the reversed *= 10; is that it jumps over the range of negative numbers and its positive again so the test if (isNegative == false && reversed < 0) does not detect this.


  • 0
    C

    correct !
    Easiest is to user a bigger container (long) and do the reversal then check if INT_MAX or INT_MIN has exceeded.


Log in to reply
 

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