您的位置:首页 > 其它

Leetcode [Add Two Numbers]

2017-09-11 13:29 260 查看

Problem:Add Two Numbers

Question

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

思路

用链表表示一个数,求两个数的和

给出的实例是 342 + 465 = 807(链表是反序的)

所以基本思路是,两个链表对应位置相加,从head加到tail,进位记为carry.

代码如下:

/**
* 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) {
int carry = 0, val = 0;
ListNode* result = new ListNode(0);
ListNode* head = result;
result->val = (l1->val + l2->val) % 10;
carry = (l1->val+l2->val) / 10;
while(l1->next != NULL || l2->next != NULL) {
if (l1->next != NULL && l2->next != NULL) {
l1 = l1->next;
l2 = l2->next;
val = l1->val+l2->val+carry;
}
else if (l1->next == NULL) {
l2 = l2->next;
val = l2->val+carry;
}
else if (l2->next == NULL) {
l1 = l1->next;
val = l1->val+carry;
}
result->next = new ListNode(val%10);
result = result->next;
carry = val/10;
}
if(carry != 0) {
result->next = new ListNode(carry);
result = result->next;
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: