# Grokking 223-2

a guest
Jun 22nd, 2022
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. class Solution {
2. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
3. int len1 = 0, len2 = 0, carry = 0;
4.
5. // Get length of l1 and l2
6. ListNode curr = l1;
7. while (curr != null) {
8. len1++;
9. curr = curr.next;
10. }
11.
12. curr = l2;
13. while (curr != null) {
14. len2 ++;
15. curr = curr.next;
16. }
17.
18. // Ensure length of l1 > length of l2
19. if (len1 < len2) {
20. curr = l1;
21. l1 = l2;
22. l2 = curr;
23.
24. int tmp = len1;
25. len1 = len2;
26. len2 = tmp;
27. }
28.
29. carry = helper(l1, l2, len1, len2);
30. if (carry > 0) {
31. return new ListNode(carry, l1);
32. }
33.
34. return l1;
35. }
36.
37. int helper(ListNode l1, ListNode l2, int len1, int len2) {
38. if (l1 == null) {
39. return 0;
40. }
41.
42. int n1 = l1.val;
43. int n2 = l2.val;
44. int carry = 0;
45.
46. if (len1 > len2) {
47. n2 = 0;
48. carry = helper(l1.next, l2, len1 - 1, len2);
49. } else {
50. carry = helper(l1.next, l2.next, len1 - 1, len2);
51. }
52.
53. l1.val = n1 + n2 + carry;
54. carry = l1.val / 10;
55. l1.val %= 10;
56.
57. return carry;
58. }
59. }