PAT甲级刷题记录——1065 A+B and C (64bit) (20分)

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: trueif A+B>C, or Case #X: falseotherwise, 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型的范围是[-263,263-1],但是题目给出的范围是[-263,263]。这里我用了《上机训练实战指南》里取巧的办法:用正溢出和负溢出的方法判断(因为加起来的数如果超过long long型的数据范围,就会发生神奇事情):

  • 当A+B≥263时,显然有A+B>C成立,但A+B会因超过long long的正向最大值而发生正溢出。由于题目给定的A和B最大均为263-1,故A+B最大为264-2,因此使用long long存储正溢出后的值的区间为[-263,-2](由(264-2)%(264)=-2可得右边界)。所以,当A>0,B>0,A+B<0时为正溢出,输出true。
  • 当A+B<-263时,显然有A+B<C成立,但A+B会因超过long long的负向最小值而发生负溢出。由于题目给定的A和B最小均为-263,故A+B最小为-264,因此使用long long存储负溢出后的值的区间为[0,263)(由(-264)%264=0可得左边界)。所以,当A<0,B<0,A+B≥0时为负溢出,输出false。

代码

#include<cstdio>
#include<stdlib.h>
#include<math.h>
#include<string>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
int main(){
    int T;
    scanf("%d", &T);
    for(int i=1;i<=T;i++){
        long long a, b, c;
        scanf("%lld%lld%lld", &a, &b, &c);
        long long tmp = a+b;
        if(a>0&&b>0&&tmp<0) printf("Case #%d: true\n", i);
        else if(a<0&&b<0&&tmp>=0) printf("Case #%d: false\n", i);
        else if(tmp>c) printf("Case #%d: true\n", i);
        else printf("Case #%d: false\n", i);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值