I have a string of signed integer value that could range from "+2147483650" to "-9638527412". I need to parse them to a 32-bit integer, such that, when the string value is above the integer capacity (2^31) it should return the nearest possible integer value. Using "Integer.parseInt" is giving out of bound exception.
Example:
input: "+2147483650"
output: "+2147483647"
input: ""-963852741258"
output: "-2147483648"
I tried to use existing functions, but I'm stuck here.
try{
//num =Integer.valueOf(stringNumber);
num =Integer.parseInt(stringNumber);
}catch(Exception e){
num = -2147483648; // if stringNumber is negative
num = +2147483647 // if stringNumber is positive
}
Since your value range is limited to "+2147483650"
to "-9638527412"
, you can parse to long
and check for overflow.
public static int parse(String stringNumber) {
long value = Long.parseLong(stringNumber);
return (value < Integer.MIN_VALUE ? Integer.MIN_VALUE :
value > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) value);
}
Test
System.out.println(parse("+2147483650"));
System.out.println(parse("42"));
System.out.println(parse("-9638527412"));
Output
2147483647
42
-2147483648