(PAT 1065) A+B and C (64bit) (整数溢出问题)

柔情只为你懂 2022-03-19 15:46 285阅读 0赞

Given three integers A, B and C in [−2^63,2^63], 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, Band 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:

  1. 3
  2. 1 2 3
  3. 2 3 4
  4. 9223372036854775807 -9223372036854775808 0

Sample Output:

  1. Case #1: false
  2. Case #2: true
  3. Case #3: false

解题思路:

整数相加溢出问题

如果两个正数相加结果<=0,则发生了溢出

如果两个负数相加结果>=0,则发生了溢出

如果正数发生了溢出,那么它们相加一定比结果要大,如果负数发生了溢出,那么它们相加一定比结果要小

分情况讨论即可

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <string>
  5. using namespace std;
  6. int main() {
  7. int N;
  8. bool flag = false;
  9. scanf("%d", &N);
  10. long long a, b, c;
  11. for (int i = 0; i < N; ++i) {
  12. scanf("%lld %lld %lld", &a, &b, &c);
  13. long long res = a + b;
  14. if (a > 0 && b > 0 && res <= 0) {
  15. flag = true;
  16. }
  17. else if (a < 0 && b < 0 && res >= 0) {
  18. flag = false;
  19. }
  20. else {
  21. if (a + b > c) {
  22. flag = true;
  23. }
  24. else {
  25. flag = false;
  26. }
  27. }
  28. if (flag) {
  29. printf("Case #%d: true\n", i + 1);
  30. }
  31. else {
  32. printf("Case #%d: false\n", i + 1);
  33. }
  34. }
  35. system("PAUSE");
  36. return 0;
  37. }

发表评论

表情:
评论列表 (有 0 条评论,285人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PAT~乙级~1065 单身狗 ~python

    目描述: “单身狗”是中文对于单身人士的一种爱称。本题请你从上万人的大型派对中找出落单的客人,以便给予特殊关爱。 输入格式: 输入第一行给出一个正整数 N(≤ ...