PAT.1065 A+B and C(64bit) (正负数溢出处理)

1065 A+B and C (64bit) (20分)

 

Given three integers A, B and C in [−], 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 (≤). 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的范围,则a + b可能会产生正负溢出。
若令sum = a + b,
如果a > 0 且b > 0,则sum溢出之后的取值范围为[(1 << 63)(这个数是longlong能表示的最大负数), -2];
a < 0 且 b < 0溢出时,范围是[0, (1 << 63) - 1];

 1 #include <cstdio>
 2 using namespace std;
 3 
 4 typedef long long ll;
 5 
 6 int main() {
 7     ll a, b, c;
 8     int t;
 9     scanf("%d", &t);
10     int _case = 0;
11     bool flag;
12     while(t --) {
13         scanf("%lld %lld %lld", &a, &b, &c);
14         ll sum = a + b;
15         if(a > 0 && b > 0 && sum < 0) flag = true;
16         else if(a < 0 && b < 0 && sum >= 0) flag = false;
17         else if(sum > c) flag = true;
18         else flag = false;
19         printf("Case #%d: ", ++ _case);
20         if(flag) printf("true
");
21         else printf("false
");
22     }
23     return 0;
24 }
 
原文地址:https://www.cnblogs.com/bianjunting/p/13036813.html