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; } };
相关文章推荐
- LeetCode --> Add Two Numbers
- LeetCode(2) Add Two Numbers实现
- leetcode——2——Add Two Numbers
- [Leetcode]Add Two Numbers
- Add Two Numbers ---LeetCode
- LeetCode 之 Add Two Numbers — C 实现
- [LeetCode] Add Two Numbers
- [LeetCode] Add Two Numbers(C++)
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode 2 Add Two Numbers
- [leetcode] 【链表】2. Add Two Numbers
- 题解——Leetcode 2. Add Two Numbers 难度:Medium
- [LeetCode] Add Two Numbers
- Add Two Numbers LeetCode第二题
- [LeetCode][2]Add Two Numbers解析 -Java实现
- leetcode 2 Add Two Numbers
- LeetCode--add-two-numbers
- LeetCode2之AddTwoNumbers的java题解