Add Two Numbers
第一次在leetcode上面做題,選了兩道最簡單的題目來試試手,回憶一下cpp的寫法。寫了一個暑假的python之後,在cpp語法上稍微有點不太習慣,還好,做完前兩道題就上手了。
這裏主要講一講Question2.
題目原意:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
這種題目以前做的也挺多,就是兩個鏈表相加,注意進位問題。
第一次寫出來的代碼是這樣的(確實有點久沒寫c++,有點生疏…):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = new ListNode(l1->val + l2->val);
ListNode* pre = ans;
ListNode* cur1 = l1->next, *cur2 = l2->next;
int carry = 0;
Carry(ans, carry);
while (cur1 != NULL || cur2 != NULL) {
ListNode* node = new ListNode(0);
if (cur1 != NULL && cur2 != NULL) {
node->val = cur1->val + cur2->val + carry;
cur1 = cur1->next;
cur2 = cur2->next;
}
else if (cur1 != NULL) {
node->val = cur1->val + carry;
cur1 = cur1->next;
}
else if (cur2 != NULL) {
node->val = cur2->val + carry;
cur2 = cur2->next;
}
pre->next = node;
pre = node;
Carry(node, carry);
}
if (carry == 1)
pre->next = new ListNode(1);
return ans;
}
void Carry(ListNode*& node, int &carry) {
if (node->val > 9) {
carry = 1;
node->val -= 10;
}
else
carry = 0;
}
};
看了答案後,發現答案的寫法確實簡潔:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummyHead = new ListNode(0);
ListNode* p = l1, * q = l2, *cur = dummyHead;
int carry = 0;
while (p != NULL || q != NULL) {
//利用三元表達式處理if語句
int x = (p != NULL)? p->val: 0;
int y = (q != NULL)? q->val: 0;
int sum = x + y + carry;
//利用除法和取餘處理多種情況
carry = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur->next;
if (p != NULL) p = p->next;
if (q != NULL) q = q->next;
}
//最後處理進位
if (carry)
cur->next = new ListNode(1);
return dummyHead->next;
}
};