LeetCode Add Two Numbersの2つのチェーンテーブルの数値加算
2129 ワード
Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
無限加算に相当し、チェーンテーブルでデータを格納します.
この問題はチェーンテーブルの操作とシミュレーション加算を試験することです.
1つ目の方法:
これは,2つの秩序チェーンテーブルを1つの秩序チェーンテーブルに統合するプログラム構造と同じである.
これは簡潔かもしれませんが、論理はあまり悪くありません.データの処理が少し違います.
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
無限加算に相当し、チェーンテーブルでデータを格納します.
この問題はチェーンテーブルの操作とシミュレーション加算を試験することです.
1つ目の方法:
これは,2つの秩序チェーンテーブルを1つの秩序チェーンテーブルに統合するプログラム構造と同じである.
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int carry = 0;
int sum = 0;
ListNode *sumList = new ListNode(-1);
ListNode *cur = sumList;
int l1val, l2val;
while (l1 && l2)
{
l1val = l1->val;
l2val = l2->val;
l1 = l1->next;
l2 = l2->next;
sum = carry + l1val + l2val;
carry = sum/10;
sum %= 10;
cur->next = new ListNode(sum);
cur = cur->next;
}
while (l1)
{
l1val = l1->val;
l1 = l1->next;
sum = carry + l1val;
carry = sum/10;
sum %= 10;
cur->next = new ListNode(sum);
cur = cur->next;
}
while (l2)
{
l1val = l2->val;
l2 = l2->next;
sum = carry + l1val;
carry = sum/10;
sum %= 10;
cur->next = new ListNode(sum);
cur = cur->next;
}
if (carry != 0)
{
cur->next = new ListNode(carry);
}
ListNode *t = sumList->next;
delete sumList;
return t;
}
これは簡潔かもしれませんが、論理はあまり悪くありません.データの処理が少し違います.
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *sumList = new ListNode(-1);
ListNode *cur = sumList;
int carry = 0;
while (l1 != nullptr || l2 != nullptr || carry != 0)
{
int l1val = l1 == nullptr ? 0 : l1->val;
int l2val = l2 == nullptr ? 0 : l2->val;
int sum = l1val + l2val + carry;
carry = sum / 10;
sum %= 10;
cur->next = new ListNode(sum);
cur = cur->next;
l1 = l1 == nullptr ? nullptr : l1->next;
l2 = l2 == nullptr ? nullptr : l2->next;
}
ListNode *t = sumList->next;
delete sumList;
return t;
}