Peck Chen

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

两数相加,负数加正数,正数回负数不会溢出

负数加负数或正数加正数才会溢出

 

负:a + b < min 溢出, 加的时候要把a或b移到min那边,因为a + b 可能会溢出

正:a + b > max 溢出, 加法同理, 开始没注意,好吧...错了

 

K = 64的最大值为特殊情况:max = 0x7fffffffffffffff(16进制);一共15个f;

 

2010-11-27 21:31:25  Accepted  21160MS  204K  504 B  C  Y

 

代码
#include <stdio.h>

int main()
{
int K;
char index;
__int64 a, b, max;

while (scanf("%d", &K) == 1)
{
max
= 1;
if (K == 64)
{
max
= 0x7fffffffffffffff;
}
else
{
max
= (max << (K - 1)) - 1;
}

scanf(
"%I64d%I64d", &a, &b);
if (((a > 0 && b > 0) && (max - a < b))
|| ((a < 0 && b < 0) && (-max - 1 - a > b)))
{
index
= '1';
}
else
{
index
= '0';
}

printf(
"%s\n", index == '1' ? "Yes" : "WaHaHa");
}

return 0;
}

 

/*Problem Description

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.
InputThere 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.
OutputFor each case, you should estimate whether the sum is beyond the range. If exceeded, print “Yes”, otherwise “WaHaHa”.

Sample Input

32

100 100


Sample Output

WaHaHa

*/

 

posted on 2010-11-29 12:05  PeckChen  阅读(590)  评论(0编辑  收藏  举报