1065 A+B and C (64bit)
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 (≤10). 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). Each line should ends with '\n'
.
- 3
- 1 2 3
- 2 3 4
- 9223372036854775807 -9223372036854775808 0
- Case #1: false
- Case #2: true
- Case #3: false
总结:因为 a b c 的取值范围是[-2^6,2^63],所以当 a b 同号的时候可能会发生溢出的情况,需要额外判断
自己的做法:利用pow(2,63)-1表示最大值与 a b相加减来判断 a b 是否越界了(也不知道是哪里出错了)
正号:a<0 && b<0 && pow(2,63)-1+a+b<0表示两数相加越界了
符号:a>0 && b>0 && pow(2,63)+a+b<0表示两数相加越界了
- #include
- #include
- using namespace std;
-
- int main(){
- int n;
- scanf("%d",&n);
-
- for(int i=1;i<=n;i++){
- long long a,b,c;
- scanf("%lld%lld%lld",&a,&b,&c);
- if(a<0 && b<0 && pow(2,63)+a+b<0) printf("Case #%d: false\n",i);
- else if(a>0 && b>0 && pow(2,63)-1-a-b<0) printf("Case #%d: true\n",i);
- else if(a+b>c) printf("Case #%d: true\n",i);
- else printf("Case #%d: false\n",i);
- }
-
- return 0;
- }
代码:
- #include
- 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;
- }
好好学习,天天向上!
我要考研!