2. Add Two Numbers
題目:
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
解析
用LinkList代表整數(shù)中每一個數(shù)字吉挣,模擬加法進位的方式進行求和計算信姓。例如:2 -> 4 -> 3
和5 -> 6 -> 4无牵,先計算個位數(shù) 2和5的和為7饥伊, 十位數(shù) 4和6的和為10谈山,逢十進一何吝,則該位的數(shù)字
為0,產生一位進位1到百位參與百位的數(shù)字求和继谚。那么百位的結果:3 + 4 + 1(這個1就是剛剛十位
相加產生的進位)烈菌,百位計算結果為8,所以最終返回結果 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* pRoot = NULL;
do {
if (l1 == NULL) {
pRoot = l2;
break;
}
if (l2 == NULL) {
pRoot = l1;
break;
}
int sum = l1->val + l2->val;
int digit = sum % 10;
int carry = sum / 10;
pRoot = new ListNode(digit);
ListNode* pTail = pRoot;
l1 = l1->next;
l2 = l2->next;
while (l1 != NULL || l2 != NULL) {
int sum = ((l1 != NULL) ? l1->val : 0) + ((l2 != NULL) ? l2->val : 0) + carry;
int digit = sum % 10;
carry = sum / 10;
ListNode* pNew = new ListNode(digit);
pTail->next = pNew;
pTail = pNew;
l1 = l1 != NULL ? l1->next : NULL;
l2 = l2 != NULL ? l2->next : NULL;
}
if (carry == 1) {
ListNode* pNew = new ListNode(carry);
pTail->next = pNew;
}
} while (false);
return pRoot;
}
};