0.聲明
該題目來源于LeetCode
如有侵權(quán),立馬刪除。
解法不唯一,如有新解法可一同討論。
1.題目
0002兩數(shù)相加
給你兩個非空的鏈表,表示兩個非負(fù)的整數(shù),它們每位數(shù)字都是按照逆序的方式存儲的,并且每個節(jié)點只能存儲一位數(shù)字。
請你將兩個數(shù)相加,并以相同形式返回一個表示和的鏈表。
你可以假設(shè)除了數(shù)字0之外,這兩個數(shù)都不會以0開頭。
示例 1:
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 465 = 807
示例 2:
輸入:l1 = [0], l2 = [0]
輸出:[0]
示例 3:
輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]文章來源:http://www.zghlxwxcb.cn/news/detail-480550.html
提示:
每個鏈表中的節(jié)點數(shù)在范圍 [1, 100] 內(nèi)
0 <= Node.val <= 9
題目數(shù)據(jù)保證列表表示的數(shù)字不含前導(dǎo)零文章來源地址http://www.zghlxwxcb.cn/news/detail-480550.html
2.代碼
namespace LeetCode_0002兩數(shù)相加
{
class Program
{
static void Main(string[] args)
{
var l1 = generateList(new int[] { 1, 5, 7 });
var l2 = generateList(new int[] { 9, 9, 2, 9 });
printList(l1);
printList(l2);
LeetCode_AddTwoNum latn = new LeetCode_AddTwoNum();
var sum = latn.AddTwoNumbers(l1, l2);
printList(sum);
var sum1 = latn.AddTwoNumbers_1(l1, l2);
printList(sum1);
Console.ReadKey();
}
static ListNode generateList(int[] vals)
{
ListNode start = null;
ListNode end = null;
for (int i = 0; i < vals.Length; i++)
{
if (start == null)//開頭為null時
{
start = new ListNode(vals[i]);
end = start;//移動指針
}
else
{
end.next = new ListNode(vals[i]);
end = end.next;
}
}
return start;
}
static void printList(ListNode l)
{
while (l != null)
{
Console.Write($"{l.val}, ");
l = l.next;
}
Console.WriteLine("");
}
}
class LeetCode_AddTwoNum
{
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
//定義一個節(jié)點用來存儲新鏈表的第一個節(jié)點
ListNode firstNode = new ListNode(0);
//定義一個循環(huán)的節(jié)點
ListNode lastnode = firstNode;
//進(jìn)位
int val = 0;
while (l1 != null || l2 != null || val != 0)
{
int num1, num2;
if (l1 == null)
num1 = 0;
else
num1 = l1.val;
if (l2 == null)
num2 = 0;
else
num2 = l2.val;
int value = num1 + num2 + val;
val = value / 10;
value = value % 10;
lastnode.next = new ListNode(value);
lastnode = lastnode.next;
if (l1 == null)
l1 = null;
else
l1 = l1.next;
if (l2 == null)
l2 = null;
else
l2 = l2.next;
}
return firstNode.next;
}
public ListNode AddTwoNumbers_1(ListNode l1, ListNode l2)
{
ListNode head = null, tail = null;
int carry = 0;
while (l1 != null || l2 != null)
{
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + carry;
if (head == null)
{
head = tail = new ListNode(sum % 10);
}
else
{
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if (l1 != null)
{
l1 = l1.next;
}
if (l2 != null)
{
l2 = l2.next;
}
}
if (carry > 0)
{
tail.next = new ListNode(carry);
}
return head;
}
}
class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
}
到了這里,關(guān)于LeetCode-C#-0002.兩數(shù)相加的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!