Solution in C++


  • 0
    A

    Following is solution in C++. I feel there is a more elegant way to handle overflow.

        class Solution {
    
        public:
            int reverse(int x) {
            int y = 0;
            bool neg = false;
            const int maxby10 = numeric_limits<int>::max() / 10;
    
            if (x < 0) {
                neg = true;
                x = x * (-1);
            }
            
            int temp, ones;
            while (x > 0) {
                ones = x % 10;
                x = x / 10;
                if ((y > maxby10) || ((y == maxby10) && (ones > 7)))
                    return 0; 
                y = y * 10 + ones;
            }
            
            if (neg) {
                temp = y;
                y = y * (-1);
                if (temp < y)
                    return 0;
            }
            
            return y;
        }
    };
    

Log in to reply
 

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