博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Check for Integer Overflow
阅读量:4151 次
发布时间:2019-05-25

本文共 998 字,大约阅读时间需要 3 分钟。

reference: 

Problem Definition:

Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.

Solution:

There can be overflow only if signs of two numbers are same, and sign of sum is opposite to the signs of numbers.

1)  Calculate sum2)  If both numbers are positive and sum is negative then return -1     Else         If both numbers are negative and sum is positive then return -1        Else return 0

Code:

/* Takes pointer to result and two numbers as    arguments. If there is no overflow, the function    places the resultant = sum a+b in “result” and    returns 0, otherwise it returns -1 */ int addOvf(int* result, int a, int b) {     *result = a + b;     if(a > 0 && b > 0 && *result < 0)         return -1;     if(a < 0 && b < 0 && *result > 0)         return -1;     return 0; }

转载地址:http://sexti.baihongyu.com/

你可能感兴趣的文章
make -n(仅列出命令, 但不会执行)用于调试makefile
查看>>
makefile中“-“符号的使用
查看>>
go语言如何从终端逐行读取数据?------用bufio包
查看>>
go的值类型和引用类型------重要的概念
查看>>
求二叉树中结点的最大值(所有结点的值都是正整数)
查看>>
用go的flag包来解析命令行参数
查看>>
来玩下go的http get
查看>>
队列和栈的本质区别
查看>>
matlab中inline的用法
查看>>
如何用matlab求函数的最值?
查看>>
Git从入门到放弃
查看>>
java8采用stream对集合的常用操作
查看>>
EasySwift/YXJOnePixelLine 极其方便的画出真正的一个像素的线
查看>>
Ubuntu系统上安装Nginx服务器的简单方法
查看>>
Ubuntu Linux系统下apt-get命令详解
查看>>
ubuntu 16.04 下重置 MySQL 5.7 的密码(忘记密码)
查看>>
Ubuntu Navicat for MySQL安装以及破解方案
查看>>
HTTPS那些事 用java实现HTTPS工作原理
查看>>
oracle函数trunc的使用
查看>>
MySQL 存储过程或者函数中传参数实现where id in(1,2,3,...)IN条件拼接
查看>>