Why does Java think that the product of all numbers from 10 to 99 is 0?

前端 未结 9 1526
悲哀的现实
悲哀的现实 2020-12-02 05:56

The following block of codes gives the output as 0.

public class HelloWorld{

    public static void main(String []args){
        int product = 1;
        fo         


        
9条回答
  •  日久生厌
    2020-12-02 06:43

    It is an integer overflow.

    The int data type is 4 bytes, or 32 bits. Therefore, numbers larger than 2^(32 - 1) - 1 (2,147,483,647) cannot be stored in this data type. Your numerical values will be incorrect.

    For very large numbers, you will want to import and use the class java.math.BigInteger:

    BigInteger product = BigInteger.ONE;
    for (long i = 10; i < 99; i++) 
        product = product.multiply(BigInteger.valueOf(i));
    System.out.println(product.toString());
    

    NOTE: For numerical values that are still too large for the int data type, but small enough to fit within 8 bytes (absolute value less than or equal to 2^(64 - 1) - 1), you should probably use the long primitive.

    HackerRank's practice problems (www.hackerrank.com), such as the Algorithms practice section, (https://www.hackerrank.com/domains/algorithms/warmup) include some very good large-number questions that give good practice about how to think about the appropriate data type to use.

提交回复
热议问题