博客
关于我
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 workbench6.3.5_MySQL Workbench
查看>>
MySQL Workbench安装教程以及菜单汉化
查看>>
MySQL Xtrabackup 安装、备份、恢复
查看>>
mysql [Err] 1436 - Thread stack overrun: 129464 bytes used of a 286720 byte stack, and 160000 bytes
查看>>
MySQL _ MySQL常用操作
查看>>
MySQL – 导出数据成csv
查看>>
MySQL —— 在CentOS9下安装MySQL
查看>>
MySQL —— 视图
查看>>
mysql 不区分大小写
查看>>
mysql 两列互转
查看>>
MySQL 中开启二进制日志(Binlog)
查看>>
MySQL 中文问题
查看>>
MySQL 中日志的面试题总结
查看>>
mysql 中的all,5分钟了解MySQL5.7中union all用法的黑科技
查看>>
MySQL 中的外键检查设置:SET FOREIGN_KEY_CHECKS = 1
查看>>
Mysql 中的日期时间字符串查询
查看>>
mysql 中索引的问题
查看>>
MySQL 中锁的面试题总结
查看>>
MySQL 中随机抽样:order by rand limit 的替代方案
查看>>
MySQL 为什么需要两阶段提交?
查看>>