This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Q2_5{ | |
public static void main(String args[]){ | |
LinkedList<Integer> test1 = new LinkedList<Integer>(); | |
LinkedList<Integer> test2 = new LinkedList<Integer>(); | |
test1.add(6); | |
test1.add(1); | |
test1.add(7); | |
test2.add(2); | |
test2.add(9); | |
test2.add(5); | |
LinkedList<Integer> sum= sum2(test1,test2); | |
System.out.println(sum.toString()); | |
} | |
// follow up question | |
public static LinkedList<Integer> sum2(LinkedList<Integer> list1, LinkedList<Integer> list2){ | |
int length1 = list1.size(); | |
int length2 = list2.size(); | |
if(length1!=length2){ | |
LinkedList<Integer> shortList = length1>length2 ? list2:list1; | |
for(int i = Math.abs(length1- length2); i>0; i--){ | |
shortList.addFirst(0); | |
} | |
} | |
LinkedList<Integer> ret = new LinkedList<Integer>(); | |
int p= sumHelper(ret,list1,list2); | |
if(p!=0) | |
ret.addFirst(p); | |
return ret; | |
} | |
private static int sumHelper(LinkedList<Integer> result,LinkedList<Integer> list1, LinkedList<Integer> list2){ | |
if(list1.isEmpty()) | |
return 0; | |
int sum = list1.poll()+list2.poll()+sumHelper(result,list1,list2); | |
result.addFirst(sum%10); | |
return sum/10; | |
} | |
//original question | |
public static LinkedList<Integer> sum1(LinkedList<Integer> list1, LinkedList<Integer> list2){ | |
LinkedList<Integer> ret = new LinkedList<Integer>(); | |
int p=0; | |
while(!list1.isEmpty() || !list2.isEmpty() || p !=0){ | |
int sumtemp =p; | |
if(!list1.isEmpty()) | |
sumtemp=sumtemp+list1.poll(); | |
if(!list2.isEmpty()) | |
sumtemp=sumtemp+list2.poll(); | |
ret.add(sumtemp%10); | |
p = sumtemp/10; | |
} | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment