2. Add Two Numbers
转载
leetcode,链表
private void BigIntAdd(string num1, string num2)
{
SLinkedList<int> slist1 = new SLinkedList<int>();
foreach (var item in num1)
{
slist1.Insert(CharUnicodeInfo.GetDecimalDigitValue(item));
}
SLinkedList<int> slist2 = new SLinkedList<int>();
foreach (var item in num2)
{
slist2.Insert(CharUnicodeInfo.GetDecimalDigitValue(item));
}
Console.WriteLine($"Input :({slist1.Head.Print()}) + ({slist2.Head.Print()})");
var rslt = AddTwoNumbers(slist1.Head, slist2.Head);
Console.WriteLine($"Output:{rslt.Print()}");
}
/// <summary>
/// 2个逆序的链表,从低位开始相加,得出结果也逆序输出,返回值是逆序结果链表的头结点。
/// </summary>
/// <param name="node1"></param>
/// <param name="node2"></param>
/// <returns></returns>
public SLinkedListNode<int> AddTwoNumbers(SLinkedListNode<int> node1, SLinkedListNode<int> node2)
{
if (node1 == null || node2 == null)
{
return null;
}
SLinkedListNode<int> head = new SLinkedListNode<int>();
var cur = head;
int carry = 0;
while (node1 != null || node2 != null)
{
int x, y;
if (node1 == null)
{
x = 0;
}
else
{
x = node1.Data;
}
if (node2 == null)
{
y = 0;
}
else
{
y = node2.Data;
}
cur.Next = new SLinkedListNode<int>((x + y + carry) % 10);
cur = cur.Next;
carry = (x + y + carry) / 10;
if (node1 != null)
{
node1 = node1.Next;
}
if (node2 != null)
{
node2 = node2.Next;
}
}
if (carry > 0)
{
cur.Next = new SLinkedListNode<int>(carry % 10);
}
return head.Next;
}
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。