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
}
CodePudding user response:
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));
}
CodePudding user response:
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.
CodePudding user response:
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)
CodePudding user response:
Try using long instead of int.
CodePudding user response:
because it overflows integer boundry