I am tasked with solving this:
write programm that checks if sum of two numbers equals the third number, prоgram needs to avoid overflow.
I figured out how to do this for cases where we have numbers with the same signs in both parts of еxpression. When we move the summator to the other side, the sign changes, and we add two ints with different signs, then an overflow is impossible in this sсenario.
But I don't know what to do if the summator and number have different signs.
bool is_sum_equal_to(int summator1, int summator2, int number) {
if (number >= 0) {
if (summator1 >= 0) {
return summator2 == number - summator1;
}
if (summator2 >= 0) {
return summator1 == number - summator2;
}
}
if (number < 0) {
if (summator1 < 0) {
return summator2 == number - summator1;
}
if (summator2 < 0) {
return summator1 == number - summator2;
}
}
}
if i understood dup post correctly correct code will be
bool is_sum_equal_to(int summator1, int summator2, int number) {
if (summator1 >= 0 && summator2 >= 0) {
if (INT_MAX - summator1 < summator2) {
return false;
}
}
else if (summator1 < 0 && summator2 < 0) {
if (summator1 < INT_MIN - summator2) {
return false;
}
}
return summator1 + summator2 == number;
}