[A]1065 A+B and C (64bit)(挖坑待填)

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


这道题如果用大整数运算,不,今天不想写了-.-
过几天再来填坑。
先记录另外一种解法(来自算法笔记):

  • 两个正数相加溢出结果为 -
  • 两个负数相加如果溢出结果为+

但是还有几个小细节需要注意:
long long的范围是[-2^63,2^63-1]

  • 如果A B的最大值均为2^63 -1 ,则A + B >= 2^64 - 2,正溢后的区间为 [-2^63,-2] ,-2是由 (2^64 - 2)% 2^64 = -2得到;
  • 如果A B的最大值均为-2^63 ,则A + B >= -2^64 ,负溢后的区间为 [0,2^63) ,0是由 (-2^64 )% 2^64 = 0得到;
    所以如果数据范围是[-2^63,2^63-1],使用这种方法我觉得会比较合理一点。

最后还有一个问题,如果直接在if语句中判断 a+b是否大于0,就不能完全通过测试点,但是如果先将a+b赋值给某个变量(如res)时,再判断res是否大于0就可以通过。网上查了也没有答案,至今未解。

code:
#include<cstdio>

int main(void){
    int n;
    long long a,b,c;
    scanf("%d",&n);
    for(int i = 1; i <= n; i++){
        scanf("%lld %lld %lld",&a,&b,&c);
        
        long long res = a + b;
        
        if(a > 0 && b > 0 && res < 0 ) {
            printf("Case #%d: true\n",i);
            continue;
        }
        if(a < 0 && b < 0 && res >= 0 ) {
            printf("Case #%d: false\n",i);
            continue;
        }

        if( a + b > c) 
            printf("Case #%d: true\n",i);
        else    printf("Case #%d: false\n",i);
    }
    
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hish/p/10251406.html