【PAT甲级】A+B and C (64bit)

Problem Description:

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: 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

解题思路:

我一开始看到题目说A,B,C都在[-{\color{Green} 2^{63}},{\color{Green} 2^{63}}]这个区间内时,只想到了要用long long型,并没有考虑到A+B后会出现数据溢出的问题,所以有俩个测试用例WA,20分只得了12分。绝望的我去看了一下柳神的代码(1065. A+B and C (64bit) (20)-PAT甲级真题)后发现这题会有俩种数据溢出的情况:令sum=A+B,①当A>0且B>0时会出现数据溢出,数据溢出后sum是个负数,此时A+B>C是成立的;②同理当A<0且B<0时也会出现数据溢出,数据溢出后sum是个正数,此时A+B肯定是小于C的。这俩种情况分别是4分。。。。。

AC代码: 12分代码:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int N;
    cin >> N;
    for(int i = 1; i <= N; i++)
    {
        long long A,B,C;
        cin >> A >> B >> C;
        printf("Case #%d: %s\n",i, A+B>C? "true" : "false");
    }
    return 0;
}

AC代码: 

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int N;
    cin >> N;
    for(int i = 1; i <= N; i++)
    {
        long long A,B,C;
        cin >> A >> B >> C;
        long long sum = A + B;
        if(A > 0 && B > 0 && sum < 0)   //sum溢出范围后为负数
        {
            printf("Case #%d: true\n",i);
        }
        else if(A < 0 && B < 0 && sum >= 0)   //sum溢出范围后为正数
        {
            printf("Case #%d: false\n",i);
        }
        else
        {
            printf("Case #%d: %s\n",i, sum>C? "true" : "false");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42449444/article/details/89966498