A1065 A+B and C (64bit) (20 point(s))

两数相加出现正溢出和负溢出

1. 原文

原题

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:

1
2
3
4
3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0

Sample output:

1
2
3
Case #1: false
Case #2: true
Case #3: false

2. 解析

给出三个整数A,B,C,判断A+B>C

由于long long范围为 [−263,263],计算机组成中指出,两个正数相加为负数,两个负数相加为正数,则为溢出。

  • A,B最大为 263-1,两数相加为264-2,超过long long正向最大值而出现正溢出,正溢出区间[-263,-2]<0,

    (264-2)%264 = -2

    return true

  • A,B最小为 -263,两数相加为-264,超过long long负向最小值而出现负溢出,负溢出区间[0,-263)>=0,

    -264%264 = 0

    return false

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<cstdio>
int main()
{
int n;
scanf("%d",&n);
long long a,b,c,sum;
for (int i = 1; i <= n; ++i)
{
scanf("%lld%lld%lld",&a,&b,&c);
printf("Case #%d: ",i);
sum=a+b;
if (a>0&&b>0&&sum<0)
{
printf("true\n");
}else if(a<0&&b<0&&sum>=0){
printf("false\n");
}else if(sum>c){
printf("true\n");
}else{
printf("false\n");
}
}
return 0;
}

本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1065/
  • 发布时间: 2019-09-03 12:33
  • 更新时间: 2021-10-29 14:03
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!