Java如何判斷整數溢出,溢出后怎么得到提示
問題
在之前刷題的時候遇見一個問題,需要解決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判斷整數溢出內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JAVA使用hutool工具實現查詢樹結構數據(省市區(qū))
今天通過本文給大家分享JAVA使用hutool工具實現查詢樹結構數據(省市區(qū)),代碼分為表結構和數據結構,代碼簡單易懂,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-08-08Java程序的初始化順序,static{}靜態(tài)代碼塊和實例語句塊的使用方式
這篇文章主要介紹了Java程序的初始化順序,static{}靜態(tài)代碼塊和實例語句塊的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01SpringCloud配置服務端的ConfigServer設置安全認證
這篇文章主要為大家介紹了SpringCloud配置服務端的ConfigServer設置安全認證,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08springboot+mybatis-plus實現內置的CRUD使用詳解
這篇文章主要介紹了springboot+mybatis-plus實現內置的CRUD使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12IntelliJ?IDEA?2024.2?發(fā)布新功能介紹Spring?Data?JPA即時查詢、自動補全cro
在2024.2?Ultimate版本中,對?Spring?Data?JPA?的支持做了增強,新功能允許您在不運行應用程序和分析日志文件的情況下查看方法將生成的查詢,下面就來一起看看這個版本中推出的幾個強大新特性2024-08-08