繁体   English   中英

如何在 java 中将十进制转换为二进制

[英]How to convert decimal to binary in java

程序的大多数输入都可以正常工作,但是当我使用大数字(例如 20)时,该值不正确。 有没有办法可以将十进制数和 output 转换为二进制? 谢谢你。

int n = Comp122.getInt("What number would you like to make a factorial?");
int factorial = 1;
for (int i = 1 ; i<=n ; i++) {
    factorial*=i;
    System.out.println(factorial);
}

您在 13 点遇到integer 溢出13! ,它超过了int可以容纳的最大数,即 2 31 (约 2.1 x 10 9 )。

您可以将变量的类型从int更改为long ,它可以容纳 2 63 (大约 1.9 x 10 19 ),但这也将超过其20!

要处理任意大的数字,请使用BigInteger class 作为变量类型。 您的代码将类似于:

BigInteger factorial = BigInteger.ONE;
for (int i = 2; i < n; i++) {
    factorial = factorial.multiply(néw BigInteger(i + ""));
}

顺便说一句,对于 output 和 integer 作为二进制或十六进制:

System.out.println(Integer.toBinaryString(n));
System.out.println(Integer.toHexString(n));

n,变得非常大,可能 Integer 无法容纳它,因为 Integer 的限制为 2,147,483.647。

这不是 output 的问题,而是您遇到了溢出。 如果您有无限的输入范围可能适合 BigInteger,您可以尝试 BigInteger。 否则,您可能想使用一些不受限制的数据结构,例如 String。 并逐位计算。

类似于: https://www.geeksforgeeks.org/multiply-large-numbers-represented-as-strings/

20 值不正确?

值为 20,= 2,432,902,008,176,640.000。

在 java 中,integer 可以正确处理小于 2,147,483,648 的任何正值。

int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647

所以,使用 int 你不能处理这种类型的大值。

long数据类型只能用于 n <= 20 的阶乘。

对于较大的 n 值,我们可以使用 java.math package 中的 BigInteger class,它可以容纳高达 2^Integer 的值:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM