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;
}
};