Skip to content

Instantly share code, notes, and snippets.

@andybrackley
Created March 2, 2022 10:12
Show Gist options
  • Save andybrackley/56cf1723f56b6ea106a3e1bc6994acb9 to your computer and use it in GitHub Desktop.
Save andybrackley/56cf1723f56b6ea106a3e1bc6994acb9 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/add-two-numbers/submissions/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null;
ListNode current = null;
int carry = 0;
while(l1 != null || l2 != null) {
var v1 = (l1?.val) ?? 0;
var v2 = (l2?.val) ?? 0;
var total = v1 + v2 + carry;
int t1 = total % 10;
var node = new ListNode(t1);
carry = total / 10;
if(current != null) {
current.next = node;
}
current = node;
if(head == null) {
head = node;
}
l1 = l1?.next;
l2 = l2?.next;
}
if(carry > 0) {
current.next = new ListNode(carry);
}
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment