Wrote a shorter version of the two number adder.

This commit is contained in:
Brandon Scott 2017-06-27 20:40:06 -05:00
parent 3be79b5a99
commit 2bc25726d2
2 changed files with 29 additions and 2 deletions

View File

@ -23,7 +23,12 @@ namespace P002_Add_Two_Numbers
input2.next = new ListNode(6);
input2.next.next = new ListNode(4);
var answer = solution.AddTwoNumbers(input1, input2);
var answer = solution.AddTwoNumbersV1(input1, input2);
for (ListNode x1 = answer; x1 != null; x1 = x1?.next)
Console.Write(x1.val + " ");
Console.Write("\n");
answer = solution.AddTwoNumbersV2(input1, input2);
for (ListNode x1 = answer; x1 != null; x1 = x1?.next)
Console.Write(x1.val + " ");
Console.Write("\n");

View File

@ -13,7 +13,7 @@ namespace P002_Add_Two_Numbers
* Status: Accepted
* Runtime: 166 ms
*/
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
public ListNode AddTwoNumbersV1(ListNode l1, ListNode l2)
{
StringBuilder result = new StringBuilder();
@ -40,5 +40,27 @@ namespace P002_Add_Two_Numbers
return head;
}
/**
* 1562 / 1562 test cases passed.
* Status: Accepted
* Runtime: 189 ms
*/
public ListNode AddTwoNumbersV2(ListNode l1, ListNode l2)
{
ListNode previous = new ListNode(0);
ListNode head = previous;
int carry = 0, value = 0;
for (ListNode x1 = l1, x2 = l2; x1 != null || x2 != null || carry != 0; x1 = x1?.next, x2 = x2?.next)
{
ListNode current = new ListNode(0);
value = (x1 != null ? x1.val : 0) + (x2 != null ? x2.val : 0) + carry;
carry = value / 10;
current.val = (value % 10);
previous = previous.next = current;
}
return head.next;
}
}
}