简体   繁体   中英

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. Is there a way I could convert the decimal numbers and output them as binary? 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! , which exceeds the largest number that an int can hold, which is 2 31 (about 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!

To handle arbitrarily large numbers, use the BigInteger class as your variable type. 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:

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.

That's not the problem of output, but rather you hit an overflow. If you have a infinite range of input that could potentially fit in a BigInteger, you could try BigInteger. Otherwise, probably you'd like to use some unlimited data structure such as String. And do the calculation digit by digit.

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

20 the value is incorrect?

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

In java, an integer can properly handle any positive value less than 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.

long datatype can be used for factorials only for 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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