Add Two Numbers
2016-01-13 15:01
281 查看
Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
用两个链表表示两个数,但是两个数都是以相反的形式表示的,链表中的每个结点保存一位数。比如342在链表中表示为2->4->3,现在求两个数相加之和,其结果也用相反的形式表示。
例如342+564 =807, 最后的链表应该是7->0->8
解题思路
两个数相加需要个位和个位相加,十位和十位相加,现在两个数都反向存储,我们每次从两个链表中找出两个数来相加得到新的数,然后生成节点保存个位数相加的结果,再去求十位数相加的结果。其中存在的问题有:
如果两个数长度不一致,那么较短的数a到达末尾的时候,最后的结果还要加上较长的数的后面部分,a的最后一位和b对应的位上数字相加产生了进位,还需要在b的下一位加上进位得到的1
如果两个数长度相等,然而也产生了进位,则需要在最后再生成一个节点来保存进位产生的数字1
代码(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) { if (l1 == NULL&&l2!=NULL) return l2; else if (l2 == NULL&&l1!=NULL) return l1; else if (l1 == NULL&&l2 == NULL) return NULL; int sum = l1->val + l2->val; int flow = 0; //保存产生的进位 if (sum >= 10) //如果相加产生进位 { sum = sum - 10; flow = 1; } ListNode* rslt = new ListNode(sum); ListNode* curPos = rslt; ListNode* a = NULL; if(l1->next !=NULL) a = l1->next; ListNode* b = NULL; if(l2->next !=NULL) b = l2->next; //开始相加 while (a != NULL&&b != NULL) { sum = a->val + b->val+flow; //产生进位 if (sum >= 10) { sum = sum - 10; flow = 1; } else flow = 0; ListNode* temp = new ListNode(sum); curPos->next = temp; curPos = curPos->next; a = a->next; b = b->next; } //如果b位数比a长 while (b != NULL) { sum = flow + b->val; if (sum >= 10) { sum = sum - 10; flow = 1; } else flow = 0; ListNode* temp = new ListNode(sum); curPos->next = temp; curPos = curPos->next; b = b->next; } //如果a位数比b长 while (a != NULL) { sum = flow + a->val; if (sum >= 10) { sum = sum - 10; flow = 1; } else flow = 0; ListNode* temp = new ListNode(sum); curPos->next = temp; curPos = curPos->next; a = a->next; } //如果最后相加产生了进位 if (flow != 0) { ListNode* temp = new ListNode(flow); flow = 0; curPos->next = temp; curPos = curPos->next; } return rslt; } };
本问题结束
相关文章推荐
- VBS 两数相加取值问题分析
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解