Question: I want to make the java program below calculate big nunbers using linkedlist. (Finish the code below) public class Node { int digit; Node next;

I want to make the java program below calculate big nunbers using linkedlist.

(Finish the code below)

public class Node {

int digit;

Node next;

public Node(int digit) {

this.digit = digit;

}

}

public class BigNumber {

Node head;

Node tail;

int size;

public BigNumber() {

this.head = null;

this.tail = null;

this.size = 0;

}

public void addDigit(int digit) {

Node newNode = new Node(digit);

if (tail == null) {

head = newNode;

tail = newNode;

} else {

tail.next = newNode;

tail = newNode;

}

size++;

}

}

public static BigNumber add(BigNumber num1, BigNumber num2) {

BigNumber result = new BigNumber();

Node curr1 = num1.head;

Node curr2 = num2.head;

int carry = 0;

while (curr1 != null || curr2 != null) {

int digit1 = (curr1 != null) ? curr1.digit : 0;

int digit2 = (curr2 != null) ? curr2.digit : 0;

int sum = digit1 + digit2 + carry;

result.addDigit(sum % 10);

carry = sum / 10;

curr1 = (curr1 != null) ? curr1.next : null;

curr2 = (curr2 != null) ? curr2.next : null;

}

if (carry > 0) {

result.addDigit(carry);

}

return result;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!