PAT 解题报告 1065. A+B and C (64bit) (20)

 A+B and C (64bit) 题目描述:

Given three integers A, B and C in [-263, 263], you are supposed to tell whether A+B > C.

给出三个整数, 判断前两个的和是不是大于第三个

算法分析:

考察溢出的检测问题, 当A和B同时为正整数或者同时为负整数的时候要小心题目的和可能溢出, 所以不能简单的return A+B > C, 要加溢出的判断代码, 弄清楚这一点以后, 就没大问题了, 溢出的检测可以参考: “如何检测整型相加溢出(overflow)”, AC代码如下:

#include <cstdio>
#include <climits>

bool gao(long long a, long long b, long long c) {
    if(a >= 0 && b >= 0) {
        if(a > LLONG_MAX - b) return true;
    }
    if(a <= 0 && b <= 0) {
        if(a < LLONG_MIN - b) return false;
    }

    return a + b > c;
}

int main() {
    long long A, B, C;
    int T;
    scanf("%d", &T);
    for(int i = 1; i <= T; ++i) {
        scanf("%lld %lld %lld", &A, &B, &C);
        printf("Case #%d: %s\n",
                i, (gao(A, B, C) ? "true" : "false") );
    }
    return 0;
}
Written on October 8, 2013