(C++)A+B and C (64bit)(思路与实现)

题目描述

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

输入描述:

The first line of the input gives the positive number of test cases, T (<=1000).  Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.


输出描述:

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).

输入例子:

3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0

输出例子:

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

思路:

首先这一个判断两个数的和是否大于第三个。而且这个A,和B、C的值都是在[-2^63, 2^63],所以这里需要使用Long来存这几个数的值,但是问题还在于,A、B两个数相加的值会超过范围,比如A+B,如果两个都是正数,那么相加后值可能超过Long的范围,然后就变成负数范围[-2^63,-2].所以我们判断如果A>0, B>0, A + B < 0,那么A+ B > C,返回True;

然后如果A + B可能超过范围,两个负的A,B然后相加大于等于0:A+ B > 0(A < 0&&B < 0);这个时候A + B的范围是[0,2^63)次方,这样一来 A  < 0 , B < 0 , A + B >=0,此时就返回false;

剩下的情况就很简单了;

 实现:

#include<stdio.h>
int main(){
  
  int T, tcase = 1;
  scanf("%d", &T);
  while(T--){
      long long a, b, c;
      scanf("%lld%lld%lld", &a, &b, &c);
      long long temp = a + b;
      bool flag;
      //注意这里是if else 多个,不能多个if。因为这样会匹配多个,导致最后错误
      if(a > 0 && b > 0 && temp < 0){
        flag = true;
      }else if(a < 0 && b < 0 && temp >= 0){
        flag = false;
      }else if(temp > c){
        flag = true;
      }else{
        flag = false;
      }
      if(flag == true){
        printf("Case #%d: true\n", tcase ++);
      }else{
        printf("Case #%d: false\n", tcase ++);
      }
     
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_28081081/article/details/80953581
今日推荐