Java integer addition subtration Overflow integer plus minus overflow

Source: Internet
Author: User

Leetcode reverse Integer, because the maximum value of int is 2 minus one, and the minimum value is 31 times of 2.

My first code put the res recursively in the try and thought there would be an exception to the overflow, but not.

Because the arguments that are passed in are of type int, and the memory and time requirements are met, long is sufficient to store the intermediate result. There's a guy on leet with a more witty overflow test (see for yourself: D)

My Code:

 Public classSolution { Public intReverseintx) {if(x<=9&&x>=-9| | X==0){            returnx; }        BooleanNagetive=false; inty=x; if(x<0) {y=-x; Nagetive=true; } arraydeque<Integer> s=NewArraydeque ();  while(y>0) {S.add (y%10); Y/=10; }        Longres=0l;  while(S.size () >=1) {res+=s.poll () *math.pow (10, S.size ()); }        if(res>integer.max_value| | res<integer.min_value) {            return0; }        returnNagetive? (int)-res: (int) Res; }}

Add method for overflow detection in Java 8.

Stack overflow:https://stackoverflow.com/questions/3001836/ How-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo

Java integer addition subtration Overflow integer plus minus overflow

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.