Advertisement
Guest User

Untitled

a guest
Jul 28th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. package com.eip.chapter8;
  2.  
  3. /*
  4. Problem: How to add 2 list based integers where the least significant digits come first
  5. Solution: - Follow normal grade school based addition
  6. */
  7. public class AddListBasedIntegers {
  8. public ListNode<Integer> addTwoNumbers(ListNode<Integer> L1, ListNode<Integer> L2) {
  9. ListNode<Integer> dummyHead = new ListNode<Integer>(0,null);
  10. ListNode<Integer> placeIter = dummyHead;
  11.  
  12. int carry = 0 ;
  13. while (L1 != null || L2 != null){
  14. int sum = carry;
  15. if(L1 != null){
  16. sum = sum + L1.data;
  17. L1 = L1.next;
  18. }
  19. if(L2 != null){
  20. sum = sum + L2.data;
  21. L2 = L2.next;
  22. }
  23. carry = sum /10;
  24. sum = sum %10;
  25. placeIter.next = new ListNode<Integer>(sum, null);
  26. placeIter = placeIter.next;
  27. }
  28.  
  29. if(carry > 0){
  30. placeIter.next = new ListNode<Integer>(carry,null);
  31. }
  32. return dummyHead.next;
  33. }
  34.  
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement