• 【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
    
    • 1
    • 2
    • 3
    • 4

    Sample Output:

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

    这题给定三个可能非常大的数 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 即由系统自动判断即可。
    代码
    #include
    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
  • 相关阅读:
    蓝桥杯刷题(十一)
    【自动驾驶】PETR 环境安装与测试
    手把手教你如何通过CC2531抓取Zigbee包,并解析加密Zigbee包
    Stable Diffusion 最新Ebsynth Utility脚本生成AI动画视频
    [UEFI]EFI_DEVICE_PATH_PROTOCOL 结构体初始化的一个例子
    AutoJs学习-QQ自动点赞及打卡
    数据结构-1()
    【多级缓存】
    C++ 基于红黑树的map和set
    【测开求职】面试题:计算机网络 精简版整理
  • 原文地址:https://blog.csdn.net/Newin2020/article/details/128214061