首页 > ACM题库 > HDU-杭电 > hdu 2116 Has the sum exceeded[解题报告]C++
2013
12-29

hdu 2116 Has the sum exceeded[解题报告]C++

Has the sum exceeded

问题描述 :

As we all know, in the computer science, an integer A is in the range of 32-signed integer, which means the integer A is between -2^31 and (2^31)-1 (inclusive), and A is a 64-signed integer, which means A is between -2^63 and (2^63)-1(inclusive). Now we give the K-signed range, and two K-signed integers A and B, you should check whether the sum of A and B is beyond the range of K-signed integer or not.

输入:

There will be many cases to calculate. In each case, there comes the integer K (2<=K<=64) first in a single line. Then following the line, there is another single line which has two K-signed integers A and B.

输出:

There will be many cases to calculate. In each case, there comes the integer K (2<=K<=64) first in a single line. Then following the line, there is another single line which has two K-signed integers A and B.

样例输入:

32
100 100

样例输出:

WaHaHa

http://acm.hdu.edu.cn/showproblem.php?pid=2116

判断两个k位带符号数的和有木有溢出。

判断的时候注意不能用两个数的和判断,否则溢出的话会有bug。

这里的方法是用最值减其中一个数,再和另一个数比较。

#include <stdio.h>
int k;
__int64 a,b;
__int64 pow(int x,int y)
{
    int i;
    __int64 s=1;
    for(i=0;i<y;i++)
        s*=x;
    return s;
}
#define MAX pow(2,63) 
int test()
{
    __int64 max,min;
    if(k==64)min=-MAX,max=MAX-1;
    else    
        min=-MAX>>k,max=(MAX>>k)-1;
    if(a==0&&b==0)return 0;
    if(a>0&&b<0)return 0;
    if(a<0&&b>0)return 0;
    if(a>0)
        return (max-a)<b;
    return (min-a)>b;
}
int main()
{
    while(~scanf("%d",&k))
    {
        scanf("%I64d%I64d",&a,&b);
        printf(test()?"Yes\n":"WaHaHa\n");
    }
    return 0;
}

 

解题转自:http://www.cnblogs.com/xiaohongmao/archive/2012/04/11/2442125.html


  1. Good task for the group. Hold it up for every yeara??s winner. This is a excellent oppotunity for a lot more enhancement. Indeed, obtaining far better and much better is constantly the crucial. Just like my pal suggests on the truth about ab muscles, he just keeps obtaining much better.