色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

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

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

瀏覽:2日期: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
主站蜘蛛池模板: 免费观看成人久久网免费观看 | 亚洲精品国产高清不卡在线 | 久久婷五月天 | 日韩一级片免费 | 亚洲一区二区三区不卡在线播放 | 99综合在线| 亚洲黄色免费观看 | 日韩欧美精品综合一区二区三区 | 特级毛片aaa免费版 特级毛片a级毛免费播放 | 99国产精品久久久久久久成人热 | 亚洲性网站 | 91精品91 | 亚洲人成在线播放网站 | 韩国一级免费视频 | 日本韩国一级 | 亚洲精品午夜久久久伊人 | 久久国产欧美 | 中文字幕一区二区三区精彩视频 | 久久久久久久久久免免费精品 | 日本一区午夜爱爱 | 成人免费的性色视频 | 亚洲欧美在线不卡 | 性生话一级国产片 | 国产精品亚洲欧美 | 成人欧美午夜视频毛片 | 欧美高清视频在线观看 | 美女的让男人桶到爽软件 | 日韩在线黄色 | 日韩在线观看视频免费 | 久久99精品视免费看 | 国产爽的冒白浆的视频高清 | 韩国美女豪爽一级毛片 | 国产在线日韩在线 | 久久久亚洲欧美综合 | 中文字幕乱码中文乱码51精品 | 日韩精品中文字幕一区三区 | 国产精品久久久久久久福利院 | 给我一个可以看片的www日本 | 国产一国产a一级毛片 | 国产手机看片 | 精品国产一区二区三区成人 |