Link to the description of the task: https://leetcode.com/problems/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 val = 0, ListNode next = null) | |
{ | |
this.val = val; | |
this.next = next; | |
} | |
} | |
public class Solution | |
{ | |
public ListNode AddTwoNumbers(ListNode firstListNode, ListNode secondListNode) | |
{ | |
var currentNodes = (first: firstListNode, second: secondListNode); | |
var carry = 0; | |
var resultFirstNode = SumNodes(currentNodes, ref carry); | |
var resultLastNode = resultFirstNode; | |
while (TryMoveForward(ref currentNodes)) | |
{ | |
Extend(ref resultLastNode, SumNodes(currentNodes, ref carry)); | |
} | |
if (carry > 0) | |
{ | |
Extend(ref resultLastNode, new ListNode(carry)); | |
} | |
return resultFirstNode; | |
} | |
private static bool HaveComeToEnd((ListNode first, ListNode second) nodes) => | |
nodes.first is null && nodes.second is null; | |
private static void Extend(ref ListNode node, ListNode extension) | |
{ | |
node.next = extension; | |
node = node.next; | |
} | |
private static bool TryMoveForward(ref (ListNode first, ListNode second) currentNodes) | |
{ | |
currentNodes.first = currentNodes.first?.next; | |
currentNodes.second = currentNodes.second?.next; | |
return !HaveComeToEnd(currentNodes); | |
} | |
private static ListNode SumNodes((ListNode first, ListNode second) nodes, ref int carry) | |
{ | |
var firstDigit = nodes.first is null ? 0 : nodes.first.val; | |
var secondDigit = nodes.second is null ? 0 : nodes.second.val; | |
var sum = SumDigits(firstDigit, secondDigit, ref carry); | |
return new ListNode(sum); | |
} | |
private static int SumDigits(int first, int second, ref int carry) | |
{ | |
var total = first + second + carry; | |
var sum = total % 10; | |
carry = (total - sum) / 10; | |
return sum; | |
} | |
} |
Conclusion:
It looks pretty nice!