Java 将 1000000000000001 转换为基数 5 时出现 NumberFormatException
Java NumberFormatException while converting 1000000000000001 to base 5
我正在尝试使用 Java:
将字符串“1000000000000001”转换为基数 5
Integer number = Integer.parseInt("1000000000000001", 5);
但是,我遇到了 NumberFormatException。该字符串已被修剪,仅包含 1 和 0。有人可以解释为什么我会收到此异常吗?
5进制数1000000000000001
等于10进制数30517578126
(你可以自己验证,也可以用online tools)。
但是,30,517,578,126
太大而不适合 int
值。最大值,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 parsable int
.
这里就是这种情况。
您需要使用 long
:
public static void main(String[] args) {
long number = Long.parseLong("1000000000000001", 5);
System.out.println(number); // prints "30517578126"
}
你可以使用BigInteger(String, int)
喜欢
System.out.println(new BigInteger("1000000000000001", 5));
输出是
30517578126
注意:即Integer.MAX_VALUE
为231-1或2147483647
.
我正在尝试使用 Java:
将字符串“1000000000000001”转换为基数 5Integer number = Integer.parseInt("1000000000000001", 5);
但是,我遇到了 NumberFormatException。该字符串已被修剪,仅包含 1 和 0。有人可以解释为什么我会收到此异常吗?
5进制数1000000000000001
等于10进制数30517578126
(你可以自己验证,也可以用online tools)。
但是,30,517,578,126
太大而不适合 int
值。最大值,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
.
这里就是这种情况。
您需要使用 long
:
public static void main(String[] args) {
long number = Long.parseLong("1000000000000001", 5);
System.out.println(number); // prints "30517578126"
}
你可以使用BigInteger(String, int)
喜欢
System.out.println(new BigInteger("1000000000000001", 5));
输出是
30517578126
注意:即Integer.MAX_VALUE
为231-1或2147483647
.