Simple solution checking overflow


  • 0
    S
    To check over we have to evaluate the following inequation (for * operation):
    isOverflow(int a, int b){
        int c = MAX_INT or 2^31 - 1
        if(a * b > c) then overflow
        or we can write in the following way to avoid overflow in * operation:
        if(a > c / b) then overlow
    }
    
    It also works on + operation:
    isOverflow(int a, int b){
        int c = MAX_INT or 2^31 - 1
        if(a + b > c) then overflow
        or we can write in the following way to avoid overflow in + operation:
        if(a > c - b) then overlow
    }
    
    bool isPalindrome(int x) {
        if(x < 0){
            return 0;
        }
        int val = 0, p = 0, tmp = x;
        while(tmp > 0){
            if(val > INT_MAX / 10){//overflow checking for *
                return 0;
            }
            val *= 10;
            if(val > INT_MAX - (tmp % 10)){//overflow checking for +
                return 0;
            }
            val += tmp % 10;
            tmp /= 10;
        }
        return (x == val);
    }

Log in to reply
 

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