1. 程式人生 > >1065 A+B and C (64bit) (20 分)溢位判定

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

題目

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資料的漏洞的人,也是牛批……