原题干:
Given three integers A, B and C in [-263, 263], 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
题目大意:大整数相加减。给定long long范围内的数字,判断第一个数字加第二个数字后是否大于第三个。
因为long long数字相加可能造成溢出,所以不可以直接判断。根据计算机原理,如果数字过大造成的溢出(正向溢出)会使得结果相加为负。而两个long long类型的正数相加造成溢出必然比一个long long数大,所以可以直接输出true。
判断long long正向溢出的方法为判断是否两个数为正数、并且两数之和为负数。
负向溢出正好和正向溢出相反。
代码如下:
#include <cstdio>
int main(){
long long a, b, c, ans;
int cnt;
scanf("%d", &cnt);
for(int i = 1; i <= cnt; i++){
scanf("%lld %lld %lld", &a, &b, &c);
ans = a + b;
if(a > 0 && b > 0 && ans < 0){ //正溢出
printf("Case #%d: true\n", i);
continue;
}else if(a < 0 && b < 0 && ans >= 0){ //负溢出
printf("Case #%d: false\n", i);
continue;
}else{
if(ans > c) printf("Case #%d: true\n", i);
else printf("Case #%d: false\n", i);
}
}
return 0;
}