user1020415
user1020415

Reputation: 33

Mathematical calculations using ArrayLists

I'd like to add (using the mathematical term) two Integer ArrayLists in Java, as well as divide them.

How would I go about this algorithmically? I can't for the life of me think of something, perhaps having to do with two's complements.

Okay, so let's say that I have large integers that are put into an ArrayLists, so to start off like 1233 and 1245. How would I divide those two with ArrayLists? a.get(i)? I could easily do it with an integer or a long, but if it had thousands of digits, that wouldn't work so well.

And yes, I'd like to add/divide the contents of the ArrayLists. If I used the get method and added them, I'd get something like [6,8,10,12] instead of that. But I guess I need to have single digits in each slot of the ArrayList. Does that explain it a bit better? It's supposed to work similarly to BigInteger class in Java.

ArrayList a = [1,2,3,4,3,4,3,5,1,3]; ArrayList b = [9,9,9,9,9,9,9,9,9,9,9];

How do I add those two into an ArrayList that should look like

ArrayList c = [1,0,1,2,3,4,3,4,3,5,1,2];

or look like c = [1,2,3,4,3,4,3,5,1,2,9,8,7,6,5,6,5,6,4,8,7];

Upvotes: 1

Views: 4508

Answers (2)

Gowtham
Gowtham

Reputation: 1475

Java has a class BigInteger that can do math with arbitrarily long numbers. Consider this instead of re-inventing.

http://docs.oracle.com/javase/1.7.0/docs/api/java/math/BigInteger.html

Upvotes: 0

Mu Mind
Mu Mind

Reputation: 11194

I'm assuming you have ArrayLists of the same length and you want to use integer addition between the elements?

for (int i = 0; i < arr1.size(); ++i) {
    arr1.set(i, arr1.get(i) + arr2.get(i));
}

Or you could make a 3rd array instead of adding to the first ArrayList in-place

ArrayList<Integer> arr3 = new ArrayList<Integer>();
for (int i = 0; i < arr1.size(); ++i) {
    arr3.add(arr1.get(i) + arr2.get(i));
}

Upvotes: 3

Related Questions