标签:
给定两个链表,链表中的数字非负,这是将两个整数由链表表示,且逆序,求两个整数的和。
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
模拟题,对应位数相加,考虑一下链表长度不同,以及进位即可
class Solution {public:ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {ListNode* res = new ListNode(0);ListNode* head = res;int carry = 0, tmpl1 = 0, tmpl2 = 0, tmpRes = 0;while (carry || l1 || l2){tmpl1 = 0;tmpl2 = 0;if (l1){tmpl1 = l1->val;l1 = l1->next;}if (l2){tmpl2 = l2->val;l2 = l2->next;}tmpRes = tmpl1 + tmpl2 + carry;head->next = new ListNode(tmpRes % 10);carry = tmpRes / 10;head = head->next;}return res->next;}};
标签:
原文地址:http://www.cnblogs.com/flyjameschen/p/4377348.html