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.
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 0Sample Output:
Case #1: false Case #2: true Case #3: false
java:
import java.util.Scanner;
import java.math.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n,cnt=0;
n=in.nextInt();
while(n!=0)
{
n=n-1;
cnt=cnt+1;
BigInteger a,b,c,sum;
a=in.nextBigInteger();
b=in.nextBigInteger();
c=in.nextBigInteger();
sum=a.add(b);
if(sum.compareTo(c)>0)
{
System.out.println("Case #"+cnt+": true");
}
else
{
System.out.println("Case #"+cnt+": false");
}
}
}
}
c++:
这是我从别的书上看到写法,很巧妙
题目中的数据范围应该是[-263, 263)
long long是有符号长整型,那么将一个长整型表示为[符号位][补码]
a<0,b<0
如果a和b是较大负数,符号位都为1,相加之后符号位虽然为0,但是由于后面补码相加的进位,符号位还为1
a和b是较小的负数,后面补码相加不会进位,而符号位是0,这时就会显示为正数,下溢
a>0,b>0
符号位为0,补码相加的进位使其变成1,显示为正数,上溢
(如果不理解的话,可以写一个求两个数相加的程序,输出一下结果看看)
在计算机内部,通常采用两位符号位来判断溢出,如果两位符号位相同,无溢出;如果为01,上溢;10,下溢
#include<iostream>
using namespace std;
int main()
{
int n,cnt=1;
cin >> n;
while(n--)
{
bool flag;
long long a,b,c,res;
cin >> a >> b >> c;
res=a+b;
if(a>0&&b>0&&res<0)
flag=true; //上溢
else if(a<0&&b<0&&res>=0)
flag=false; //下溢
else if(res>c)
flag=true;
else
flag=false;
if(flag)
cout << "Case #" << cnt++ << ": true" << endl;
else
cout << "Case #" << cnt++ << ": false" << endl;
}
return 0;
}