veena schulz
veena schulz

Reputation: 11

Arithmatic operations on java collection objects

The programming question is

Given two numbers represented by two lists, write a function that returns sum list. The sum list is list representation of addition of two input numbers.

Input: First List: 5->6->3 // represents number 563 Second List: 1->4->2 // represents number 142 Output Resultant list: 7->0->5 // represents number 705

I have tried using collections but got stuck during addition of collection objects. Any suggestion please?

import java.util.*;
import java.io.*;
public class Listdemo{
public static void main(String[] args){
    LinkedList<Integer> l1 = new LinkedList<Integer>();
    LinkedList<Integer> l2 = new LinkedList<Integer>();
    Scanner i1 = new Scanner(System.in);
    System.out.println("Enter first list values:");
    while(i1.hasNextInt()){
         int i = i1.nextInt();
         l1.add(i);
        }
    Scanner i2 = new Scanner(System.in);
    System.out.println("Enter second list values:");
    while(i2.hasNextInt()){
         int i = i2.nextInt();
         l2.add(i);
         }
    Iterator r1 = l1.iterator();
    Iterator r2 = l2.iterator();
    while(r1.hasNext() && r2.hasNext()){
         int j= r1.next() + r2.next();
         System.out.println(j);
         }

Upvotes: 1

Views: 54

Answers (1)

Jack Billings
Jack Billings

Reputation: 21

What you are wanting to do is "Arbitrary Precision Arithmetic". Essentially, each element in your lists corresponds to a position in a base 10 number. Assuming both lists are the same length (have the same number of digits), you would want to add the corresponding digits and if there is a "carry" (9+5 has a carry of 4), you would add that to the next element in the list.

Upvotes: 1

Related Questions