Non-elegant solution but handles Overflow condition properly without cheating


  • 0
    P

    Here is a slightly longer solution in C++ which handles overflow situation without being dependent on long long or other language specific implementations like the most voted solutions.

    class Solution {
    public:
        int reverse(int x) {
            
            long num = 0;
            bool neg = false;
            int copy = x;
            
            if(x < 0) {
                neg = true;
                x = x * -1; // Won't work if input is INT_MIN
            }
            
            while(x) {
                int quo = x%10;
                x = x/10;
                
                if (INT_MAX - num*10 - quo < 0) {
                    num = 0;
                    break;
                }
                
               // In case given input is  INT_MIN.
                if(x < 0 && num*10 + quo - INT_MIN > 0) {
                    num = 0;
                    break;
                }
                num = num*10 + quo;
                
            }
            
            if (neg)
                num = -1 * num;
                
            return num;
            
        }
    };
    
    

Log in to reply
 

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