Created
February 21, 2017 11:56
-
-
Save linnet8989/68e0711244bf9a3d61216614c441459e to your computer and use it in GitHub Desktop.
2. Add Two Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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