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
一开始写也不知道可以直接判断相加溢出以及溢出怎么样,所以写成了字符串相加形式。
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
using namespace std;string add(string aa,string bb)
{int i=aa.size()-1,j=bb.size()-1;string res="";int flag=0;while(i>=0&&j>=0){int tp=aa[i]-'0'+bb[j]-'0'+flag;flag = 0;if(tp>=10)flag = 1;int yu = tp%10;char ch[100];sprintf(ch,"%d",yu);res=ch+res;i--;j--;}while(i>=0){int tp=aa[i]-'0'+flag;flag = 0;if(tp>=10){flag=1;}int yu = tp%10;char ch[100];sprintf(ch,"%d",yu);res=ch+res;i--;}while(j>=0){int tp=bb[j]-'0'+flag;flag=0;if(tp>=10){flag=1;}int yu = tp%10;char ch[100];sprintf(ch,"%d",yu);res=ch+res;j--;}if(flag == 1){res = string("1")+res;}//cout<<"resL "<<res<<endl;return res;
}int main()
{//add("123","9999");int k,cnt=0;string a,b,c;cin>>k;while(cnt<k){cnt++;string left="0",right="0";cin>>a>>b>>c;if(a[0] == '-'){a.erase(0,1);right = add(right,a);}else{left = add(left,a);}// cout<<"left: "<<left<<" right: "<<right<<endl;if(b[0] == '-'){b.erase(0,1);right = add(right,b);}else{left = add(left,b);}//cout<<"left: "<<left<<" right: "<<right<<endl;if(c[0] == '-'){c.erase(0,1);left = add(left,c);}else{right = add(right,c);}// cout<<"left: "<<left<<" right: "<<right<<endl;printf("Case #%d: ",cnt);if(left.size()>right.size()){printf("true\n");}else if(left.size() == right.size()){if(left<=right){ printf("false\n");}else{printf("true\n");}}else{printf("false\n");}}return 0;
}
数字的范围是[?2^?63??,2?^63??], 而long long 的范围是[-2^63,2^63),两个数相加会溢出,符号位会取反。 先判断会溢出的情况,注意两个最大的负数相加会导致结果为0,故负数相加判断时要判断大于等于0,而最大正数溢出导致的是负数,只需要判断是否小于0即可。
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
using namespace std;int main()
{//add("123","9999");int k,cnt=0;long long a,b,c;cin>>k;while(cnt<k){cnt++;cin>>a>>b>>c;long long ab = a+b;cout<<"res:"<<ab<<endl;if(a>0&&b>0&&ab<0){printf("Case #%d: true\n",cnt);}else if(a<0&&b<0&&ab>=0){printf("Case #%d: false\n",cnt);}else if(ab>c){printf("Case #%d: true\n",cnt);}elseprintf("Case #%d: false\n",cnt);}return 0;
}