This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #85 Check if integer addition will overflow
Write boolean function addingWillOverflow which takes two integers x, y and return true if (x+y) overflows.
An overflow may be above the max positive value, or below the min negative value.
bool addingWillOverflow(int x, int y) {
return ((x > 0) && (y > INT_MAX - x)) ||
((x < 0) && (y < INT_MIN - x));
}
INT_MAX and INT_MIN are defined in limits.h header, bool type is defined in stdbool.h
bool addingWillOverflow(int x, int y)
{
bool result;
core.checkedint.adds(x, y, result);
return result;
}
func addingWillOverflow(x int, y int) bool {
if x > 0 {
return y > math.MaxInt-x
}
return y < math.MinInt-x
}
public boolean addingWillOverflow(int x, int y){
boolean willOverFlow = false;
if(x > 0 && y > 0){
if(y > (Integer.MAX_VALUE - x)){
willOverFlow = true;
}
}
if(x < 0 && y < 0){
if(y < (Integer.MIN_VALUE - x)){
willOverFlow = true;
}
}
return willOverFlow;
}
If both values are positive, make sure the difference between one and the MAX_VALUE is less than the other, otherwise they will overflow.
If both values are negative, make sure the difference between one and the MIN_VALUE is less than the other, otherwise they will underflow.
The case where one is negative and one is positive does not need to be checked as they will definitely not under or overflow in that scenario.
If both values are negative, make sure the difference between one and the MIN_VALUE is less than the other, otherwise they will underflow.
The case where one is negative and one is positive does not need to be checked as they will definitely not under or overflow in that scenario.
boolean willOverflow(int x, int y) {
try {
addExact(x, y);
subtractExact(x, y);
return false;
} catch (ArithmeticException e) {
return true;
}
}
def adding_will_overflow(x,y):
return False
Python has arbitrary precision integers so you shouldn't worry about overflow.
Also, don't bother coding this constant function!
Also, don't bother coding this constant function!