Given three integers a, b and c (all of them are 64 bit signed integers, to ), check if a + b > c.
Since a + b can overflow (or underflow) easily (when the sum is too big or too small to hold using a 64 bit signed integer), we should avoid this.
1 2 3 4 5 6 7 8 9 | bool chk(long long a, long long b, long long c) { if(a >= 0 && b >= 0) { if(a > LLONG_MAX - b) return true; } if(a <= 0 && b <= 0) { if(a < LLONG_MIN - b) return false; } return a + b > c; } |
bool chk(long long a, long long b, long long c) { if(a >= 0 && b >= 0) { if(a > LLONG_MAX - b) return true; } if(a <= 0 && b <= 0) { if(a < LLONG_MIN - b) return false; } return a + b > c; }
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
215 wordsloading...
Last Post: Why Absolute Value of INT_MAX and INT_MIN is different?
Next Post: Coding Exercise - 1. Life, the Universe, and Everything - Learning LUA programming language