C++ solution without using long, with overflow check


  • 0
    M
    class Solution {
    public:
        int reverse(int x) 
        {
            int output = 0, last = 0;
            while(x)
            {
                last = output;          // store last output before overflow
                output = (output * 10) + (x % 10);
                if(output / 10 != last) // backtrack and ckeck again if overflowing
                    return 0;
                x /= 10;
            }
            return output;
        }
    };
    
    

Log in to reply
 

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