Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the overflow of adding integers in Java

Shulou Source: shulou.com Published: 2022-06-01 20:41:01 09月23日 Update

This article mainly introduces "how to solve Java integer addition overflow". In daily operation, I believe that many people have doubts about how to solve the problem of Java integer addition overflow. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubt of "Java integer addition overflow". Next, please follow the editor to study!

The problem encountered a problem when doing exercises before. We need to solve how to determine whether there is an overflow after int is added. If there is an overflow, return the Integer.MAX_VALUE solution. JDK8 has helped us implement Math. I have to say that this method is found in StackOverflow. It is indeed much better than some domestic forums to add 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;} at this point, the study on "how to solve the Java integer additive overflow" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Integers learning problems methods more help practical next multiplication subtraction addition articles solutions time theory knowledge articles websites solutions Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Technology Huawei NVidia Apple