A1065. A+B and C (64bit) (20)
题目描述
Given three integers A, B and C in [-263, 263), you are supposed to tell whether A+B > C.
输入描述:
The first line of the input gives the positive number of test cases, T (<=1000). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.
输出描述:
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).
输入例子:
3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0
输出例子:
Case #1: false
Case #2: true
Case #3: false
我的思路
需知 long long 的范围是 [-2^63, 2^63) ,因此边界会出现溢出。
当 A>0 , B>0, A+B<0 时为正溢出,溢出后的值的区间为 [-2^63 , -2],输出true。
当 A<0 , B<0, A+B>=0 时为负溢出,溢出后的值的区间为 [0 , 2^63],输出false。
我的代码
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int T;
long long A, B, C, D;
bool r[1000]={0};
scanf("%d", &T);
for (int i=1; i<=T; i++)
{
scanf("%lld %lld %lld", &A, &B, &C);
D = A+B;
if (D>C)
{ //正常情况下
r[i] = 1;
}
//判断是否溢出
if ((A>0)&&(B>0)&&(D<0))
{ //正溢出
r[i] = 1;
}else if ((A<0)&&(B<0)&&(D>=0))
{ //负溢出
r[i] = 0;
}
}
for (int i=1; i<=T; i++)
{
printf("Case #%d: %s", i, r[i]?"true":"false");
if (i!=T)
{
printf("\n");
}
}
return 0;
}