博客
关于我
java语言——如何判断整数溢出
阅读量:339 次
发布时间:2019-03-04

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

????????????????????????????????????????????????

??

public static int addExact(int x, int y) {    int r = x + y;    // ???????    boolean overflow = ( (x ^ r) > 0 ) != ( (y ^ r) > 0 );    if (overflow) {        throw new ArithmeticException("integer overflow");    }    return r;}

??

public static int subtractExact(int x, int y) {    int r = x - y;    // ???????    boolean overflow = ( (x ^ r) > 0 ) != ( (y ^ r) > 0 );    if (overflow) {        throw new ArithmeticException("integer overflow");    }    return r;}

??

public static int multiplyExact(int x, int y) {    long r = (long)x * (long)y;    if ( (int)r != r ) {        throw new ArithmeticException("integer overflow");    }    return (int)r;}

?????

public static long multiplyExact(long x, long y) {    long r = x * y;    // ???????    if ( (x == 0 || y == 0) ) {        return r;    }    // ???????    long ax = Math.abs(x);    long ay = Math.abs(y);    if ( (ax > Integer.MAX_VALUE / ay) || (ay > Integer.MAX_VALUE / ax) ) {        // ????        long temp = r / y;        if ( (y != 0) && (temp != x) ) {            throw new ArithmeticException("long overflow");        }        // ??????        if (x == Long.MIN_VALUE && y == -1) {            throw new ArithmeticException("long overflow");        }    }    return r;}

??

  • ?????????x?y???r?????????????????????????????

  • ???????????????????????

  • ??????????????????????????????

  • ?????????????????????????Long.MIN_VALUE?-1????

??????????????????????????????????????

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

你可能感兴趣的文章
MySQL事务及其特性与锁机制
查看>>
mysql事务理解
查看>>
MySQL事务详解结合MVCC机制的理解
查看>>
MySQL事务隔离级别:读未提交、读已提交、可重复读和串行
查看>>
MySQL事务隔离级别:读未提交、读已提交、可重复读和串行
查看>>
webpack css文件处理
查看>>
mysql二进制包安装和遇到的问题
查看>>
MySql二进制日志的应用及恢復
查看>>
mysql互换表中两列数据方法
查看>>
mysql五补充部分:SQL逻辑查询语句执行顺序
查看>>
mysql交互式连接&非交互式连接
查看>>
MySQL什么情况下会导致索引失效
查看>>
Mysql什么时候建索引
查看>>
MySql从入门到精通
查看>>
MYSQL从入门到精通(一)
查看>>
MYSQL从入门到精通(二)
查看>>
mysql以下日期函数正确的_mysql 日期函数
查看>>
mysql以服务方式运行
查看>>
mysql优化--索引原理
查看>>
MySQL优化之BTree索引使用规则
查看>>