Alkarin - 1 year ago 61

Java Question

I have an arrayDeque of BigInts which I have implemented as essentially just holding strings IE

`BigInt@Instancewhatever = "3476234236734567"`

I already have a method to add one BigInt to another which returns a new BigInt, containing a String of the sum of the two BigInts.

IE

`BigInt@1 = "4321"`

BigInt@2 = "5555"

BigInt@Sum = "9876"

My question is how can I Iterate through this Deque and call add on the BigInts.

I was thinking of using a forloop on the size of the ArrayDeque, but ArrayDeque doesn't really have a

`x.get(x.size()-1)`

Edit:For more extrapolation, this is what I am currently working with.

digit is the List format of the string IE

`"1,2,3,4","5,5,5,5"`

`public BigInt times(BigInt operand){`

List<Integer> a = this.getDigit();

List<Integer> b = operand.getDigit();

//sum left unused atm

List<Integer> sum = operand.getDigit();

Deque<BigInt> temp = new ArrayDeque<>();

Deque<BigInt> temp1 = new ArrayDeque<>();

if(a.size() > b.size()){

temp1 = multiply(a,b,temp);

//Iterate here?

} else {

temp1 = multiply(b,a,temp);

//Iterate here?

}

return new BigInt(temp1.toString());

}

Answer Source

`ArrayDeque<T>`

implements `Iterable<T>`

, hence you can use a for-each loop over it:

```
ArrayDeque<BigInt> deque = new ArrayDeque<BigInt>();
//populate deque
BigInt sum = new BigInt("0");
for(BigInt b : deque) {
sum = sum.add(b);
}
//sum now holds the sum of the elements in deque.
```

This assumes your `BigInt`

class has a method `add(BigInt b)`

. Either you have implemented it, or perhaps you meant to use `BigInteger`

, the built in class for large ints.

A more advanced way to sum up the elements in the deque is to use stream reduction operations and method references:

```
ArrayDeque<BigInt> deque = new ArrayDeque<>();
//populate deque...
BigInteger sum = deque.stream().reduce(new BigInt("0"), BigInt::add);
```