zoukankan      html  css  js  c++  java
  • A1065. 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, weparated by single spaces

    输出格式

      For each test case, ouput in one lin "Case #X: true" if A + B >C, or "Case #X: false" otherwise, where X is the case number (starting from 1)

    输入样例

    3

    1 2 3

    2 3 4

    9223372036854775807 -9223372036854775808 0

    输出样例

    Case #1: false

    Case #1: true

    Case #1: false

    题意

      给出三个整数A,B,C,如果A + B > C,则输出true;否则,输出 false

    基本思路

      long long 的范围是[-263, 263),因此题目给出的两个整数可能会溢出(正溢出或负溢出),直接判断大小会造成错误。

      在计算机组成原理中指出

    • 如果两个正数之和等于负数,或者两个负数之和等于正数,那么就是溢出

    当 A + B ≥ 263时,显然有 A+B>C成立,但A+B因为超过long long的正向最大值而发生正溢出,题目给定的A和B最大均为263 - 1,故A+B最大为264 - 2,因此使用 long long 存储正向溢出后的值得区间为[-263, -2] (由(264 - 2)%(264)=-2可得右边界),所以当A > 0,B > 0,A + B < 0时为正溢出,输出true

    当 A + B < -263时,显然有 A + B < C成立,但A + B会因超过 long long 的负向最小值而发生负溢出。由于题目给定的A和B最小均为 -263,故A+B最小为-264,因此使用long long 存储负溢出后的值的区间为[0, 263) (由(-246)%264=0可得左边界),所以,当 A < 0,B < 0,A + B ≥ 0 时为负溢出,输出false

    在没有溢出的情况下,当A + B > C时,输出true;当A + B ≤ C时,输出false

    #include <bits/stdc++.h>
    int main(int argc, char *argv[]) {
        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;
            bool flag = flag;
            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
            }
        } 
        return 0;    
    }

    题目关键

    • 如果两个正数之和等于负数,或者两个负数之和等于正数,那么就是溢出
  • 相关阅读:
    grep取缩写|awk两个文件取交集
    p{space}|p{Hex}|p{Digit}|转译符|1|g{-1}|[^ab]|/([^dD]+)/
    线性回归的简单实现mxnet
    线性回归从0实现——mxnet
    决策树(DT)
    C++基本语法(三)存储类及运算符
    C++基本语法(二)数据类型及变量类型、常量
    C++基本语法(一)
    np.zeros((a,b,c))
    python之range()
  • 原文地址:https://www.cnblogs.com/YC-L/p/12151611.html
Copyright © 2011-2022 走看看