Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array form of integer

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
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading