public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { int carry = 0; if (l1 != null) { carry += l1.val; l1 = l1.next; } if (l2 != null) { carry += l2.val; l2 = l2.next; } ListNode l3 = new ListNode(carry % 10); ListNode res = l3; carry /= 10; while (l1 != null || l2 != null) { if (l1 != null) { carry += l1.val; l1 = l1.next; } if (l2 != null) { carry += l2.val; l2 = l2.next; } l3.next = new ListNode(carry % 10); l3 = l3.next; carry /= 10; } if (carry != 0) { l3.next = new ListNode(carry % 10); } return(res); }
static void Main(string[] args) { var solution = new Solution(); // Input: l1 = [2, 4, 3], l2 = [5, 6, 4] // Output:[7,0,8] // Explanation: 342 + 465 = 807. var l1 = new ListNode(2, new ListNode(4, new ListNode(3))); var l2 = new ListNode(5, new ListNode(6, new ListNode(4))); Console.WriteLine(string.Join(", ", ListToList(solution.AddTwoNumbers(l1, l2)))); // Input: l1 = [0], l2 = [0] // Output:[0] l1 = new ListNode(0); l2 = new ListNode(0); Console.WriteLine(string.Join(", ", ListToList(solution.AddTwoNumbers(l1, l2)))); // Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] // Output:[8,9,9,9,0,0,0,1] l1 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))))))); l2 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))); Console.WriteLine(string.Join(", ", ListToList(solution.AddTwoNumbers(l1, l2)))); }
public ListNode(int val = 0, ListNode next = null) { this.val = val; this.next = next; }