Skip to main content
Java 8+'s
Source Link
cellepo
  • 181
  • 1
  • 5

All other Answers here (as of this writing) are valid. But if you are Java 8+, you probably would want to be even more precise with Java 8's8+'s Math.addExact(int, int):

public static boolean canSumToInt(int me, int... args){
    for(int curArg: args){
        try{
            me = Math.addExact(me, curArg);
        }catch(ArithmeticException ae){
            return false;
        }
    }
    return true;
}

Overflow would throw ArithmeticException.

All other Answers here (as of this writing) are valid. But if you are Java 8+, you probably would want to be even more precise with Java 8's Math.addExact(int, int):

public static boolean canSumToInt(int me, int... args){
    for(int curArg: args){
        try{
            me = Math.addExact(me, curArg);
        }catch(ArithmeticException ae){
            return false;
        }
    }
    return true;
}

Overflow would throw ArithmeticException.

All other Answers here (as of this writing) are valid. But if you are Java 8+, you probably would want to be even more precise with Java 8+'s Math.addExact(int, int):

public static boolean canSumToInt(int me, int... args){
    for(int curArg: args){
        try{
            me = Math.addExact(me, curArg);
        }catch(ArithmeticException ae){
            return false;
        }
    }
    return true;
}

Overflow would throw ArithmeticException.

Source Link
cellepo
  • 181
  • 1
  • 5

All other Answers here (as of this writing) are valid. But if you are Java 8+, you probably would want to be even more precise with Java 8's Math.addExact(int, int):

public static boolean canSumToInt(int me, int... args){
    for(int curArg: args){
        try{
            me = Math.addExact(me, curArg);
        }catch(ArithmeticException ae){
            return false;
        }
    }
    return true;
}

Overflow would throw ArithmeticException.