-1

I was trying to convert the array to integer sum=999999999999 (twelve 9) , when i am limiting the array to less than ten 9s it is giving the result but when i am giving the array of more than ten 9s it is giving an unexpected result , please explain it will be really helpful for me

int[] arr={9,9,9,9,9,9,9,9,9,9,9,9};
int p=arr.length-1;
int m;
int num=0;
for (int i = 0; i <= p; i++) {
    m=(int) Math.pow(10, p-i);
    num += arr[i]*m;           // it is executing like: 900+90+9=999
}
Debankan
  • 81
  • 8

5 Answers5

2

this happens because you're exceeding the Integer.MAX_VALUE.

You can read about it here.

You can use instead of int a long, to store large values, and if that is not enough for you, you can use - BigInteger

BigInteger num = BigInteger.valueOf(0);
for (int i = 0; i <= p; i++) {
    BigInteger m = BigInteger.valueOf((int) Math.pow(10, p-i));
    BigInteger next =  BigInteger.valueOf(arr[i]).multiply(m));
    num = num.add(BigInteger.valueOf(arr[i]*m));
}
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
1

A couple of things.

  • You don't need to use Math.pow.
  • for up to 18 digits, you can use a long to do the computation.
  • I added some extra digits to demonstrate
int[] arr={9,9,9,9,9,9,9,9,9,9,9,9,1,1,2,3,4};

long sum = 0;             // or BigInteger sum = BigInteger.ZERO;
for (int val : arr) {
    sum = sum * 10 + val; // or sum.multiply(BigInteger.TEN).add(BigInteger.valueOf(val));
}
System.out.println(sum);

prints

99999999999911234

Here is the sequence for 1,2,3,4 so you can see what is happening.

- sum = 0
- sum = sum(0) * 10 + 1 (sum is now 1)
- sum = sum(1) * 10 + 2 (sum is now 12)
- sum = sum(12)* 10 + 3 (sum is now 123)
- sum = sum(123)*10 + 4 (sum is now 1234)
WJS
  • 36,363
  • 4
  • 24
  • 39
0

It is because an int is coded on 4 byte so technically you can only go from -2,147,483,648 to 2,147,483,647. Consider using the long type.

cdelaby
  • 11
  • 2
-1

Try using long (or any other type which can represent larger numbers) instead of int. I suggest this because the int overflows: see https://en.wikipedia.org/wiki/Integer_overflow

Bernd
  • 2,113
  • 8
  • 22
YoavK
  • 23
  • 6
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 31 '22 at 18:44
-2

Because it overflows integer boundry. The maximum integer value that can be stored in Java is 2147483647. When you try to store a value greater than this, the result will be an unexpected value. To solve this issue, you can use a long data type instead of an int data type

you can read about it here and here

sinanorl
  • 143
  • 1
  • 9