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^63),题目里的右闭区间是错的(至于原理,计算机组成原理之定点数的补码表示)。但是并不影响解题。
只有A、B只做加法,所以A、B同符号时才可能有溢出。而且负溢出时才可能取到0。
其他解法:long double法、位运算法、string数字运算法 (详情查牛客网)
#include<iostream>
#include<string>
using namespace std;
//这题要考虑溢出,除了本方法外,还有可以解决问题的办法有:long double法、位运算法、string数字运算法 (详情查牛客网)
int main() {
int T;
long long A,B,C,sum;
string f="false",t="true",s;
cin>>T;
for(int i=0;i<T;i++){
cin>>A>>B>>C;
sum=A+B;
printf("Case #%d: ",i+1);
if(A>0&&B>0&&sum<0){
s=t;
}else if(A<0&&B<0&&sum>=0){//负数溢出时,才可能取到0
s=f;
}else{
s=sum>C?t:f;
}
cout<<s<<endl;
}
return 0;
}