A possible good way to handle overflow without type conversion


  • 0
    R

    I am thinking of a way to handle the overflow without converting the results to unsigned or long long. The OJ did not give test cases for this issue; Please let me know, if there is any error.

     int reverse(int x) {
        int sum = 0;
    	while ( x != 0) {
    	    if (x>0 &&(sum > INT_MAX/10 || (sum == INT_MAX/10 && x%10 > INT_MAX%10))) return INT_MAX; // or 0 ? -1?
    	    if (x<0 &&(sum < INT_MIN/10 || (sum == INT_MIN/10 && x%10 < INT_MIN%10))) return INT_MIN;
            sum = sum*10 + x%10;
            x /= 10;
        }
    	return sum;
    }

Log in to reply
 

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