8ms C++ solution considering overflow


  • 4
    P
    class Solution {
    public:
        int reverse(int x) {
            int y = 0;
            while (x != 0) {
                auto rest = x % 10;
    
                if (x > 0) {
                    if (y > ((INT_MAX - rest) / 10)) {
                        return 0;
                    }
                } else {
                    if (y < ((INT_MIN - rest) / 10)) {
                        return 0;
                    }
                }
    
                y = y * 10 + rest;
                x /= 10;
            }
    
            return y;
        }
    };
    

Log in to reply
 

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