PAT A1065 A+B and C (64bit) (20)
来源:互联网 发布:python 获取局域网ip 编辑:程序博客网 时间:2024/06/06 19:35
题目地址:https://www.patest.cn/contests/pat-a-practise/1065
题目描述:
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 0
输出样例(Sample Output):
Case #1: false
Case #2: true
Case #3: false
题意:
给出三个整数 A,B,C,如果 A + B > C,则输出 true;否则,输出 false。
解题思路:
由于 long long 的范围是[-263,263],因此题目中给出的两个整数相加有可能会溢出(正溢出或负溢出),直接进行大小判断会造成错误。
对于溢出后的具体范围,可以进行如下分析:
当 A + B >= 263 时,显然有 A + B > C 成立,但 A + B 会因超过 long long 的正向最大值而发生正溢出。所以,当 A > 0,B > 0,A + B < 0 时为正溢出,输出 true。
当 A + B < -263 时,显然有 A + B < C 成立,但 A + B 会因超过 long long 的负向最小值而发生负溢出。所以,当 A < 0,B < 0,A + B >= 0 时为负溢出,输出 false。
在没有溢出的情况下,当 A + B > C 时,输出 true;当 A + B <= C 时,输出 false
C++完整代码如下:
#include <cstdio>int main(){ int T, tcase = 1; scanf("%d", &T); while(T--){ long long a, b, c; scanf("%lld%lld%lld", &a, &b, &c); long long res = a + b; // res 存放 a + b 的结果 bool flag; if(a > 0 && b > 0 && res < 0) flag = true; //正溢出为 true else if(a < 0 && b < 0 && res >= 0) flag = false; //负溢出为 false else if(res > c) flag = true; //无溢出时,A + B > C 时为 true else flag = false; //无溢出时,A + B <= c 时为 false if(flag == true){ printf("Case #%d: true\n", tcase++); }else{ printf("Case #%d: false\n", tcase++); } } return 0;}
- PAT A1065 A+B and C (64bit) (20)
- 【PAT】A1065. A+B and C (64bit) (20)
- PAT A1065. A+B and C (64bit) (20)
- PAT-A1065 A+B and C (64bit)(模拟)
- PAT A1065. A+B and C (64bit)
- PAT---A1065 A+B and C(20)
- PAT A 1065. A+B and C (64bit) (20)
- PAT-A 1065. A+B and C (64bit) (20)
- PAT-A-1065. A+B and C (64bit) (20)
- PAT A+B and C (64bit)
- 【PAT】1065. A+B and C (64bit) (20)
- 浙大PAT 1065. A+B and C (64bit) (20)
- PAT 1065. A+B and C (64bit) (20)
- PAT 1065. A+B and C (64bit) (20)
- ZJU-PAT 1065. A+B and C (64bit) (20)
- PAT 1065. A+B and C (64bit) (20)
- PAT 1065. A+B and C (64bit) (20)
- PAT 1065. A+B and C (64bit) (20)
- 哈夫曼
- IOS 如何避免Block的循环引用
- iOS 实现不定参数方法
- java中String类为什么要设计成final
- Java学习笔记(22)Developing Efficient Algorithms
- PAT A1065 A+B and C (64bit) (20)
- 【Codeforces 612A】The Text Splitting
- ubuntu搭建scikit-learn环境及pydev+eclipse
- 响应式布局简单代码
- 删数--约瑟夫环-- 华为2016研发工程师编程题
- SQL 查询的结果某个字段是Null,用默认的值代替
- ajax传数据和图片(base64格式)
- 实习点滴 - 破窗理论、C++ 函数模板静态库
- LogMonitor