Guest User

Untitled

a guest
Feb 15th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. /**
  2. * Definition for singly-linked list.*/
  3. function ListNode(val) {
  4. this.val = val;
  5. this.next = null;
  6. }
  7.  
  8. /**
  9. You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
  10.  
  11. You may assume the two numbers do not contain any leading zero, except the number 0 itself.
  12.  
  13. Follow up:
  14. What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
  15.  
  16. Example:
  17.  
  18. Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
  19. Output: 7 -> 8 -> 0 -> 7
  20. */
  21. var addTwoNumbers = function(l1, l2) {
  22. if (!l1 && !l2) return null;
  23. var arr1 = buildArr(l1);
  24. var arr2 = buildArr(l2);
  25. if(arr1.length != arr2.length) padding(arr1, arr2);
  26.  
  27. var carry = 0;
  28. var sum = 0;
  29. var curr = null;
  30. var output = null;
  31. var i = 0;
  32. while (i < arr1.length || carry > 0){
  33. sum += carry;
  34. if (i !== arr1.length) sum += arr1[i] + arr2[i];
  35. carry = 0;
  36. if (sum > 9){
  37. carry = Math.floor(sum/10);
  38. sum = sum%10;
  39. }
  40.  
  41. curr = new ListNode(sum)
  42. sum = 0;
  43. if(output){
  44. curr.next = output;
  45. }
  46. output = curr;
  47. i++;
  48. }
  49. return output;
  50. };
  51.  
  52. function buildArr(l){
  53. if(!l) return [];
  54. var arr = [];
  55. while(l){
  56. arr.unshift(l.val);
  57. l = l.next;
  58. }
  59. return arr;
  60. }
  61.  
  62. function padding(arr1,arr2){
  63. var diff = Math.abs(arr1.length - arr2.length);
  64. var modArr = (arr1.length > arr2.length) ? arr2 : arr1;
  65. for (var i = 0; i < diff; i++){
  66. modArr.push(0);
  67. }
  68. }
  69.  
  70. var l1 = new ListNode(5);
  71. var l2 = new ListNode(5);
  72. addTwoNumbers(l1,l2); // 1 -> 0
Add Comment
Please, Sign In to add comment