简体   繁体   English

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

[英]How to convert decimal to binary in java

Most inputs to the program work fine but when i use large numbers eg 20 the value is incorrect.程序的大多数输入都可以正常工作,但是当我使用大数字(例如 20)时,该值不正确。 Is there a way I could convert the decimal numbers and output them as binary?有没有办法可以将十进制数和 output 转换为二进制? Thank you.谢谢你。

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);
}

You're encountering integer overflow at 13!您在 13 点遇到integer 溢出13! , which exceeds the largest number that an int can hold, which is 2 31 (about 2.1 x 10 9 ). ,它超过了int可以容纳的最大数,即 2 31 (约 2.1 x 10 9 )。

You can change the type of your variable from int to long , which can hold 2 63 (about 1.9 x 10 19 ), but that too will exceed its limit at 20!您可以将变量的类型从int更改为long ,它可以容纳 2 63 (大约 1.9 x 10 19 ),但这也将超过其20!

To handle arbitrarily large numbers, use the BigInteger class as your variable type.要处理任意大的数字,请使用BigInteger class 作为变量类型。 Your code would then something like:您的代码将类似于:

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

By the way, to output an integer as binary or hex:顺便说一句,对于 output 和 integer 作为二进制或十六进制:

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

n, becomes very big and probably Integer cannot hold it as Integer has a limitation of 2,147,483.647. n,变得非常大,可能 Integer 无法容纳它,因为 Integer 的限制为 2,147,483.647。

That's not the problem of output, but rather you hit an overflow.这不是 output 的问题,而是您遇到了溢出。 If you have a infinite range of input that could potentially fit in a BigInteger, you could try BigInteger.如果您有无限的输入范围可能适合 BigInteger,您可以尝试 BigInteger。 Otherwise, probably you'd like to use some unlimited data structure such as String.否则,您可能想使用一些不受限制的数据结构,例如 String。 And do the calculation digit by digit.并逐位计算。

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

20 the value is incorrect? 20 值不正确?

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

In java, an integer can properly handle any positive value less than 2,147,483,648.在 java 中,integer 可以正确处理小于 2,147,483,648 的任何正值。

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

So, using int you can not handle this type of big value.所以,使用 int 你不能处理这种类型的大值。

long datatype can be used for factorials only for n <= 20. long数据类型只能用于 n <= 20 的阶乘。

For larger values of n, we can use the BigInteger class from the java.math package, which can hold values up to 2^Integer.MAX_VALUE:对于较大的 n 值,我们可以使用 java.math package 中的 BigInteger class,它可以容纳高达 2^Integer 的值:

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

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