午夜剧场伦理_日本一道高清_国产又黄又硬_91黄色网战_女同久久另类69精品国产_妹妹的朋友在线

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

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

瀏覽:27日期: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在线 | 欧美日韩精品在线视频 | 日日cao| 99er这里只有精品 | 污视频导航 | 色六月婷婷 | 一级片在线| 国产黄色网络 | 亚洲综合精品 | 国产第5页 | 青青草日本 | 少妇高潮一区二区三区 | 草在线| 日本精品久久久久久 | 久久久午夜影院 | 亚洲一二三视频 | 成人亚洲欧美 | 91丨九色丨丰满人妖 | 久久视频在线观看免费 | 伊人网综合网 | 欧美一级二级三级 | 一级黄色淫片 | 久久黄色一级视频 | 亚洲自拍偷拍综合 | 久久精品99国产精品日本 | av一二三四 | 欧美成人女星 | 国产影视一区 | 国产久草视频 | 亚洲成人伦理 | 免费在线播放av | 日韩精品国产一区 | 成人性毛片 | 国产热视频 | 韩国精品在线 | 国产精品v亚洲精品v日韩精品 | 一级片黄色| 91精品婷婷国产综合久久蝌蚪 | 亚洲3级|