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

您的位置:首頁技術(shù)文章
文章詳情頁

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

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

問題

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

解決方案

JDK8已經(jīng)幫我們實現(xiàn)了Math下,不得不說這個方法是在StackOverflow找到了的,確實比國內(nèi)一些論壇好多了

加法

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; }

如何使用?

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

寫這個的目的

總結(jié)一下,也方便告訴他人Java幫我們寫好了函數(shù)。

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

標(biāo)簽: Java
主站蜘蛛池模板: 日韩免费在线观看视频 | 99久热 | 99久久精品久久亚洲精品 | 99国产精品自拍 | 超碰2020 | 日韩亚洲一区二区三区 | 欧美中文 | 国产高清av | 99久久久国产精品免费蜜臀 | 美日韩三级 | 亚洲激情另类 | a在线观看免费 | 老司机午夜影院 | 亚洲成人免费看 | 福利视频一区二区 | 黄色成人18| 久久久久久久伊人 | 成人午夜免费在线观看 | 97国产视频 | 91免费福利视频 | 欧美成人精品在线 | 国产女人高潮毛片 | 在线激情av| 黄色免费网站在线观看 | 97偷拍视频 | 久久无 | 国产福利二区 | 欧美日韩在线观看一区二区 | 91精品免费看 | 91视频在线网站 | 精品一区二三区 | 久草一区二区 | 五月天综合在线 | 久久久中文字幕 | xxx一区| 久久免费视频观看 | 青草视频在线免费观看 | 男生操女生免费网站 | 久一久久| 成人黄色在线 | 国产a网站|