I am trying to convert the String "1000000000000001" to base 5 using Java:
Integer number = Integer.parseInt("1000000000000001", 5);
However, I am gettig NumberFormatException. The string is trimmed and only contains 1 and 0. Could someone please explain why am I getting this exception?
The number 1000000000000001
in base 5 is equivalent to the number 30517578126
in base 10 (you can verify this yourself or use online tools).
However, 30,517,578,126
is too big to fit in an int
value. The maximal value, Integer.MAX_VALUE
is 2,147,483,647
. This explains the exception you are getting - from parseInt
:
throws
NumberFormatException
- if the String does not contain a parsableint
.
which is the case here.
You need to use a long
:
public static void main(String[] args) {
long number = Long.parseLong("1000000000000001", 5);
System.out.println(number); // prints "30517578126"
}