1065 A+B and C (64bit) (20 分)溢出判定

版权声明:假装这里有个版权声明…… https://blog.csdn.net/CV_Jason/article/details/85336372

题目

Given three integers A, B and C in [ 2 63 , 2 63 ] [−2^{63},2^{63}] , you are supposed to tell whether A + B > C 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,计算相加之后是否满足A+B>C 。
  解题思路: 这道题最常规的思路应该是超大数运算,因为题目给的范围是超过整型的最大存储值的。但是如果用超大数计算,这道题太麻烦了,20分的题这么花时间,值不值得呢。网上给出了一种另辟蹊径的做法,利用溢出的特性,以及这道题的漏洞来解。
  要知道——
  1. 正数相加向上溢出最后得到的是一个负数,比如——

  在这里插入图片描述
  如果a>0,b>0,但是结果得到的却是个负值,显然a+b>c,因为c的最大值是 2 63 2^{63} ,a+b溢出,显然是超过这个最大值了;
  2. 第二种情况,如果是负数相加向下溢出,得到的是正值,显然a+b<c,同理,超出c的最小值了,必定是小于的;
  3. 最后一种情况,就是不溢出,直接判断是否满足a+b>c。

/*
** @Brief:No.1062 of PAT advanced level.
** @Author:Jason.Lee
** @Date:2018-12-28
** @Solution: Accepted!
*/
#include<iostream>

using namespace std;

int main(){
	int N;
	long long a,b,c;
	while(cin>>N){
		for(int i=0;i<N;i++){
			bool equal = false;			
			cin>>a>>b>>c;
			long long add = a+b;
			if(a>0&&b>0&&add<=0) equal = true;
			else if(a<0&&b<0&&add>=0) equal = false;
			else if(add>c) equal = true;
			cout<<"Case #"<<i+1<<": ";
			cout<<(equal?"true":"false")<<endl;
		}
	}
	return 0;
} 

在这里插入图片描述

总结

  能想出来溢出这种特性,并找到PAT数据的漏洞的人,也是牛批……

猜你喜欢

转载自blog.csdn.net/CV_Jason/article/details/85336372