Given three integers A, B and C in [−2^63,2^63], you are supposed to tell whether A+B>C.
Input Specification:
The first line of the input gives the positive number of test cases, T (≤10). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.
Output Specification:
For each test case, output in one line Case #X: true
if A+B>C, or Case #X: false
otherwise, where X is the case number (starting from 1).
Sample Input:
3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0
Sample Output:
Case #1: false
Case #2: true
Case #3: false
思路
- 当正溢出时,A + B 大小的范围区间为 [2^63, 2^64 - 2],所以溢出后的区间为 [-2^63, -2]。所以,当 A > 0, B > 0, A + B < 0 时,为正溢出,输入 true。
- 当负溢出时,A + B 大小的范围区间为 [-2^64, -2^63 - 1],所以溢出后的区间为 [0, 2^63 - 1]。所以,当 A < 0, B < 0, A + B >= 0 时为,为负溢出,输出 false。
- 在没有溢出的情况下,正常比较。
注意点
- A + B 必须存放到 long long 型变量中才可与 C 进行比较,而不可以在 if 的条件中直接相加与 C 比较,否则会造成后两组数据错误。
#include <cstdio>
int main() {
int t;
long long a, b, c;
bool flag;
scanf("%d", &t);
for (int i = 1; i <= t; i++) {
scanf("%lld %lld %lld", &a, &b, &c);
long long res = a + b;
if (a > 0 && b > 0 && res < 0) {
flag = true;
} else if (a < 0 && b < 0 && res >= 0) {
flag = false;
} else if (res > c) {
flag = true;
} else {
flag = false;
}
printf("Case #%d: %s\n", i, flag ? "true" : "false");
}
return 0;
}