My ac code of Reverse Integer and some thoughts


  • 0
    1
    int testMul(int a, int b){
        return !a || a * b / a == b;
    }
    
    int testAdd(int a, int b){
        int sum = a + b;
        int negOverflow = a < 0 && b < 0 && sum >= 0;
        int posOverflow = a >= 0 && b >= 0 && sum <= 0;
        return !negOverflow && !posOverflow;
    }
    
    int reverse(int x) {
        int res = 0;
        if(!x) return 0;
        if(x % 10 == 0) while(x % 10 == 0) x /= 10;
        while(x){
            if(!testMul(res, 10)) return 0;
            if(!testAdd(res * 10, x % 10)) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
    

    I use 2 functions to solve the overflow problem.A little long but useful.
    However, has anyone concluded a simpler way?


Log in to reply
 

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