【PAT 甲級】1065 A+B and C (64bit) (20)

A1065. A+B and C (64bit) (20)

 

題目描述

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

 

我的思路

 需知 long long 的範圍是 [-2^63, 2^63) ,因此邊界會出現溢出

 當 A>0 , B>0, A+B<0 時爲正溢出,溢出後的值的區間爲 [-2^63 , -2],輸出true。 

 當 A<0 , B<0, A+B>=0 時爲負溢出,溢出後的值的區間爲 [0 , 2^63],輸出false。

 

我的代碼

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
	int T;
	long long A, B, C, D;
	bool r[1000]={0};
	scanf("%d", &T);
	
	for (int i=1; i<=T; i++)
	{
		scanf("%lld %lld %lld", &A, &B, &C);
		D = A+B;
		if (D>C)
		{  //正常情況下 
			r[i] = 1;
		}
		//判斷是否溢出 
		if ((A>0)&&(B>0)&&(D<0)) 
		{  //正溢出 
			r[i] = 1;
		}else if ((A<0)&&(B<0)&&(D>=0))
		{  //負溢出 
			r[i] = 0;
		}
	}
	
	for (int i=1; i<=T; i++)
	{
		printf("Case #%d: %s", i, r[i]?"true":"false");
		if (i!=T)
		{
			printf("\n");
		} 
	}
		
	return 0;
 } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章