最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2020年10月19日 10:06:43   作者:Aaron_濤  
這篇文章主要介紹了Java如何判斷整數(shù)溢出,溢出后怎么得到提示,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

問題

在之前刷題的時候遇見一個問題,需要解決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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

海宁市| 分宜县| 庆云县| 高邑县| 涞水县| 凯里市| 扬中市| 鹰潭市| 磐石市| 瓮安县| 庐江县| 合作市| 大埔县| 东阳市| 博野县| 衢州市| 潢川县| 留坝县| 东阳市| 德州市| 亚东县| 营口市| 聊城市| 榕江县| 民丰县| 东宁县| 新兴县| 吉首市| 英德市| 马尔康县| 五家渠市| 睢宁县| 安远县| 濉溪县| 明光市| 安徽省| 淅川县| 濉溪县| 上犹县| 海兴县| 抚松县|