博客
关于我
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的错误:No query specified
查看>>
mysql监控工具-PMM,让你更上一层楼(上)
查看>>
mysql监控工具-PMM,让你更上一层楼(下)
查看>>
MySQL相关命令
查看>>
mysql社工库搭建教程_社工库的搭建思路与代码实现
查看>>
Warning: Can't perform a React state update on an unmounted component. This is a no-
查看>>
mysql笔记 (早前的,很乱)
查看>>
MySQL笔记:InnoDB的锁机制
查看>>
mysql第一天~mysql基础【主要是DDL、DML、DQL语句,以及重点掌握存存引擎、查询(模糊查询)】
查看>>
mysql第二天~mysql基础【查询排序、分页查询、多表查询、数据备份与恢复等】
查看>>
MySQL简介和安装
查看>>
MySQL简单查询
查看>>
MySQL管理利器 MySQL Utilities 安装
查看>>
MySQL篇(管理工具)
查看>>
mysql类型转换函数convert与cast的用法
查看>>
mysql系列一
查看>>
MySQL系列之数据授权(安全)
查看>>
MySQL系列之数据类型(Date&Time)
查看>>