Skip to content

Instantly share code, notes, and snippets.

@linnet8989
Created February 21, 2017 11:56
Show Gist options
  • Save linnet8989/68e0711244bf9a3d61216614c441459e to your computer and use it in GitHub Desktop.
Save linnet8989/68e0711244bf9a3d61216614c441459e to your computer and use it in GitHub Desktop.
2. Add Two Numbers
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
public class Solution
{
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
int c = 0;
ListNode l = new ListNode(0);
ListNode head = l;
while (l1.next != null | l2.next != null)
{
l.next = new ListNode((c + l1.val + l2.val) % 10);
c = (c + l1.val + l2.val) / 10;
l = l.next;
if (l1.next == null)
{
l1.val = 0;
}
else
{
l1 = l1.next;
}
if (l2.next == null)
{
l2.val = 0;
}
else
{
l2 = l2.next;
}
}
l.next = new ListNode((c + l1.val + l2.val) % 10);
c = (c + l1.val + l2.val) / 10;
l = l.next;
if (c != 0)
{
l.next = new ListNode(c);
l = l.next;
}
return head.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment