1065 A+B and C (64bit) (20 分)

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

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的範圍是[-263, 263),所以題目中給出的兩個整數相加有可能會溢出(正溢出或負溢出),直接進行大小判斷會形成錯誤。在計算機組成原理中會指出,若是兩個正數之和等於負數或是兩個負數之和等於正數,那麼就是溢出。測試

對於溢出後的具體範圍,能夠進行以下分析:
①當A+B≥2^63時,顯然有A+B>C成立,但A+ B會因超過long long的正向最大值而發生正溢出。因爲題目給定的A和B最大均爲263-1,故A+B最大爲264-2,所以使用long long存儲正溢出後的值的區間爲[-263, -2] (由(264 - 2)%(264)= -2可得右邊界)。因此,當A>0,B>0,A+B<0時爲正溢出,輸出true。
②當A+B<-263時,顯然有A+B<C成立,但A+ B會因超過long long的負向最小值而發生負溢出。因爲題目給定的A和B最小均爲263,故A+ B最小爲264,所以使用longlong存儲負溢出後的值的區間爲[0, 263) (由( -264)%264=0可得左邊界)。因此,當A<0,B<0,A+ B≥0時爲負溢出,輸出false.
③在沒有溢出的狀況下,當A+B>C時,輸出true; 當A+B≤C時,輸出false.spa

  • 注意點
    ①經測試,數據中並無A或B取到263的狀況,所以題目中的數據範圍多是寫錯了,應該是[- 263, 263)才更符合數據,不然就要用帶負數的大整數運算了(由於long long 存儲263時會自動變成- 263,沒法區分左右邊界)。
    ②A+ B必須存放到long long型變量中才可與C進行比較,而不能夠在if的條件中直
    接相加與C比較,不然會形成後兩組數據錯誤。

參考代碼

  • 1號:注意long long類型的變量,要用%lld
#include<stdio.h>
int main(){
	int t;
	scanf("%d", &t);
	long long a[10], b[10], c[10];
	for(int i = 0; i < t; i++){
		scanf("%lld %lld %lld", &a[i], &b[i], &c[i]);
		}
	for(int i = 0; i < t; i++){
		long long sum;
		sum = a[i] + b[i];
		if(a[i] > 0 && b[i] > 0 && sum < 0) printf("Case #%d: true\n", i + 1);
		else if(a[i] < 0 && b[i] < 0 && sum >= 0) printf("Case #%d: false\n", i+1);
		else if(sum > c[i])	printf("Case #%d: true\n", i + 1);
		else printf("Case #%d: false\n", i + 1);
	}	
	return 0;
}
  • 2號:更加簡單,其實不須要用數組,在循環的時候就有i能夠引用code

    #include <cstdio>
    using namespace std;
    int main() {
    	int n;
         scanf("%d", &n);
         for(int i = 0; i < n; i++) {
         	long long a, b, c;
         	scanf("%lld %lld %lld", &a, &b, &c);
         	long long sum = a + b;
    	 	if(a > 0 && b > 0 && sum < 0) {
         		printf("Case #%d: true\n", i + 1);
         	} else if(a < 0 && b < 0 && sum >= 0){
         		printf("Case #%d: false\n", i + 1);
        	} else if(sum > c) {
         		printf("Case #%d: true\n", i + 1);
         	} else {
         		printf("Case #%d: false\n", i + 1);
         	}
         }
         return 0;
    }
相關文章
相關標籤/搜索