Handle Overflow


  • 0
    A

    I think there are 2 ways to deal with overflow.

    1. check if you are ABOUT to overflow before adding:

      if (result == Integer.MAX_VALUE/10 && x%10 > Integer.MAX_VALUE%10)
      return 0;
      if (result > Integer.MAX_VALUE/10)
      return 0;

    2. trickier way, declare 'result' as long, and check if exceeds Integer.MAX_VALUE. Just remember to cast back to int when returning.

    Any other options?


  • 0
    N

    What abt ;

    if( result > ( INT_MAX - remainder ) / 10 ) // overflow
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.