【PAT甲级 - C++题解】1065 A+B and C (64bit)

简介: 【PAT甲级 - C++题解】1065 A+B and C (64bit)

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.


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). Each line should ends with '\n'.


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 是否成立。


思路

这道题可以利用语言的底层特性,如果两个非常大的正整数相加可能会溢出,因为底层是用二进制补码进行存储,所以相加后的结果一旦溢出就会变成负数,同理如果两个非常小的负整数进行相加也可能溢出,相加后的结果一旦溢出就会变成正数,因此可以归纳为如下结论:


1.若 a≥0,b≥0,a+b<0 ,则 a+b 一定大于 c ,因为 c 在整数范围内,而 a+b 正数已经溢出了,所以一定比在范围内的 c 大。

2.若 a<0,b<0,a+b>=0 ,则 a+b 一定小于 c ,因为 c 在整数范围内,而 a+b 负数已经溢出了,所以一定比在范围内的 c 小。

3.若 a+b 没有发生溢出,那么 a+b 的结果就可以正常表示出来,直接返回 a+b<c 即由系统自动判断即可。


代码

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int n;
//判断a+b是否大于c
bool check(LL a, LL b, LL c)
{
    LL d = a + b;
    if (a >= 0 && b >= 0 && d < 0) return true;    //正向溢出
    else if (a < 0 && b < 0 && d >= 0)  return false;   //反向溢出
    return a + b > c;   //没有发生溢出
}
int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        LL a, b, c;
        scanf("%lld %lld %lld", &a, &b, &c);
        if (check(a, b, c))    printf("Case #%d: true\n", i);
        else    printf("Case #%d: false\n", i);
    }
    return 0;
}
目录
相关文章
|
数据处理 C++
C++-bit转hex(四位二进制转十六进制)
C++-bit转hex(四位二进制转十六进制)
442 0
|
C++
【PAT甲级 - C++题解】1040 Longest Symmetric String
【PAT甲级 - C++题解】1040 Longest Symmetric String
303 0
|
算法 C++
【PAT甲级 - C++题解】1044 Shopping in Mars
【PAT甲级 - C++题解】1044 Shopping in Mars
382 0
|
C++
【PAT甲级 - C++题解】1117 Eddington Number
【PAT甲级 - C++题解】1117 Eddington Number
363 0
|
存储 C++ 容器
【PAT甲级 - C++题解】1057 Stack
【PAT甲级 - C++题解】1057 Stack
331 0
|
存储 C++
【PAT甲级 - C++题解】1055 The World‘s Richest
【PAT甲级 - C++题解】1055 The World‘s Richest
257 0
|
C++
【PAT甲级 - C++题解】1051 Pop Sequence
【PAT甲级 - C++题解】1051 Pop Sequence
304 0
|
人工智能 BI C++
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
511 0
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
758 12