日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > java >内容正文

java

java 加法 溢出_StackOverflow热帖:Java整数相加溢出怎么办?Java8一步搞定~

發(fā)布時(shí)間:2023/12/2 java 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 加法 溢出_StackOverflow热帖:Java整数相加溢出怎么办?Java8一步搞定~ 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

閱讀本文大概需要 2 分鐘。

作者:Aaron_濤

問(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ù)。

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的java 加法 溢出_StackOverflow热帖:Java整数相加溢出怎么办?Java8一步搞定~的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。