【PAT甲级 - C++题解】1065 A+B and C (64bit)

✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1065 A+B and C (64bit) (pintia.cn)
🔑中文翻译:A + B 和 C
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

1065 A+B and C (64bit)

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). Each line should ends with '\n'.

Sample Input:

3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0

Sample Output:

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

这题给定三个可能非常大的数 a,b,c ,需要我们判断 a+b>c 是否成立。

思路

这道题可以利用语言的底层特性,如果两个非常大的正整数相加可能会溢出,因为底层是用二进制补码进行存储,所以相加后的结果一旦溢出就会变成负数,同理如果两个非常小的负整数进行相加也可能溢出,相加后的结果一旦溢出就会变成正数,因此可以归纳为如下结论:

  1. a≥0,b≥0,a+b<0 ,则 a+b 一定大于 c ,因为 c 在整数范围内,而 a+b 正数已经溢出了,所以一定比在范围内的 c 大。
  2. a<0,b<0,a+b>=0 ,则 a+b 一定小于 c ,因为 c 在整数范围内,而 a+b 负数已经溢出了,所以一定比在范围内的 c 小。
  3. a+b 没有发生溢出,那么 a+b 的结果就可以正常表示出来,直接返回 a+b<c 即由系统自动判断即可。
代码
#include<bits/stdc++.h>
using namespace std;

typedef long long LL;
int n;

//判断a+b是否大于c
bool check(LL a, LL b, LL c)
{
    LL d = a + b;
    if (a >= 0 && b >= 0 && d < 0) return true;    //正向溢出
    else if (a < 0 && b < 0 && d >= 0)  return false;   //反向溢出
    return a + b > c;   //没有发生溢出
}

int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        LL a, b, c;
        scanf("%lld %lld %lld", &a, &b, &c);
        if (check(a, b, c))    printf("Case #%d: true\n", i);
        else    printf("Case #%d: false\n", i);
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值