PAT A1065 A+B and C (64bit)

mac2024-05-26  40

前言

传送门

正文

题目描述

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

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,263-1],故两数相加可能会溢出(正溢出/负溢出),当a,b均大于0,而a+b<0,此时为正溢出;当a,b均小于0,而a+b>=0,此时为负溢出。而易知,正溢出时,a+b必定大于c,而负溢出时a+b必定小于c

参考题解:

/* 注意正溢出和负溢出的问题 */ #include<cstdio> #define LL long long int main(){ LL a,b,c,sum; int t,count=1; scanf("%d",&t); bool flag; while(t--){ scanf("%lld%lld%lld",&a,&b,&c); sum=a+b; if(a>0&&b>0&&sum<0)flag=true; else if(a<0&&b<0&&sum>=0)flag=false; else if(a+b>c)flag=true; else flag=false; if(flag==true){ printf("Case #%d: true\n",count++); }else{ printf("Case #%d: false\n",count++); } } return 0; }

后记

穿越人海,只为与你相拥; 此刻已皓月当空,爱的人手捧星光; 我知他乘风破浪,去了黑暗一趟

最新回复(0)