亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

Java如何判斷整數溢出,溢出后怎么得到提示

瀏覽:5日期:2022-08-22 15:14:55

問題

在之前刷題的時候遇見一個問題,需要解決int相加后怎么判斷是否溢出,如果溢出就返回Integer.MAX_VALUE

解決方案

JDK8已經幫我們實現了Math下,不得不說這個方法是在StackOverflow找到了的,確實比國內一些論壇好多了

加法

public static int addExact(int x, int y) { int r = x + y; // HD 2-12 Overflow iff both arguments have the opposite sign of the result if (((x ^ r) & (y ^ r)) < 0) { throw new ArithmeticException('integer overflow'); } return r; }

減法

public static int subtractExact(int x, int y) { int r = x - y; // HD 2-12 Overflow iff the arguments have different signs and // the sign of the result is different than the sign of x if (((x ^ y) & (x ^ r)) < 0) { 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; }

注意 long和int是不一樣的

public static long multiplyExact(long x, long y) { long r = x * y; long ax = Math.abs(x); long ay = Math.abs(y); if (((ax | ay) >>> 31 != 0)) { // Some bits greater than 2^31 that might cause overflow // Check the result using the divide operator // and check for the special case of Long.MIN_VALUE * -1 if (((y != 0) && (r / y != x)) ||(x == Long.MIN_VALUE && y == -1)) {throw new ArithmeticException('long overflow'); } } return r; }

如何使用?

直接調用是最方便的,但是為了追求速度,應該修改一下,理解判斷思路,因為異常是十分耗時的操作,無腦異常有可能超時

寫這個的目的

總結一下,也方便告訴他人Java幫我們寫好了函數。

到此這篇關于Java如何判斷整數溢出,溢出后怎么得到提示的文章就介紹到這了,更多相關Java判斷整數溢出內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Java
主站蜘蛛池模板: 中国黄色a| 狠狠综合久久久久综合小说网 | 一级特黄国产高清毛片97看片 | 特黄特a级特别特级特毛片 特黄特色一级aa毛片免费观看 | 久久日本经典片免费看 | 亚洲永久| 成人免费一级在线播放 | 爱爱爱免费视频观看在线网站 | 国产第一页久久亚洲欧美国产 | 性欧美视频在线观看 | 国产露脸对白91精品 | 一级毛片在线看在线播放 | 国产在线观看一区精品 | 久久我们这里只有精品国产4 | 黄色片子网站 | 亚洲欧洲色图 | 麻豆观看| 五月婷婷俺也去开心 | 欧美一级毛片免费播放aa | 成人视屏网站 | 日本美女a级片 | 青青热久免费精品视频在线观看 | 国产香港三级理论在线 | 日本一级片在线播放 | 国产激烈无遮挡免费床戏视频 | 色 综合 欧美 亚洲 国产 | 性综合网 | 国产欧美激情一区二区三区 | 亚洲第一区在线 | 精品视自拍视频在线观看 | 亚洲天堂啪啪 | 丝袜美腿亚洲综合 | 欧美视频黑鬼大战白妞 | 国产不卡在线 | 成人看片| 黄色小视频观看 | 午夜精品视频5000 | 亚洲图片欧洲图片aⅴ | 国产三级a三级三级 | 亚洲一区不卡视频 | 俄罗斯aa一级毛片 |