久久福利_99r_国产日韩在线视频_直接看av的网站_中文欧美日韩_久久一

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

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

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

問(wèn)題

在之前刷題的時(shí)候遇見(jiàn)一個(gè)問(wèn)題,需要解決int相加后怎么判斷是否溢出,如果溢出就返回Integer.MAX_VALUE

解決方案

JDK8已經(jīng)幫我們實(shí)現(xiàn)了Math下,不得不說(shuō)這個(gè)方法是在StackOverflow找到了的,確實(shí)比國(guó)內(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)該修改一下,理解判斷思路,因?yàn)楫惓J鞘趾臅r(shí)的操作,無(wú)腦異常有可能超時(shí)

寫(xiě)這個(gè)的目的

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

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

標(biāo)簽: Java
主站蜘蛛池模板: 91成人在线 | 久久久网| 国产精品久久久久久久久久10秀 | 91精品国产91久久综合桃花 | 女人夜夜春高潮爽av片 | 中文字幕乱码一区二区三区 | 午夜不卡福利视频 | 国产三区在线视频 | 精品视频久久 | 国产中文一区 | 欧美综合一区二区 | 一区二区免费视频 | 人妖天堂狠狠ts人妖天堂狠狠 | 成人免费xxxxx在线视频软件 | 成人h动漫免费观看网站 | 99久久99久久精品国产片果冻 | 国产精品三级久久久久久电影 | 91精品视频一区 | 欧美色综合一区二区三区 | 在线观看日韩精品 | 玖玖精品| 毛片一区二区三区 | 亚洲一区二区三区在线播放 | 中文一区 | 99精品欧美一区二区蜜桃免费 | 999精品在线| 日韩精品小视频 | 日韩成人一区二区 | 亚洲 中文 欧美 日韩 在线观看 | 国产精品成人久久久久 | 大香伊在人线免97 | 久久久国产一区 | 这里只有精品在线视频观看 | 日韩成人精品在线 | 久久久久久久国产 | 91麻豆精品国产91久久久更新时间 | 麻豆沈芯语在线观看 | 国产电影一区二区在线观看 | 一区二区三区在线 | 日韩一区二区在线免费 | 欧美一级久久 |