LeetCode---两数相加
2019-04-12 22:11
295 查看
题目:
官方答案(c++):
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* dummyHead=new ListNode(0); ListNode* p=l1,*q=l2,*curr=dummyHead; int carry=0; while(p!= NULL || q!=NULL) { int x=(p!=NULL)?p->val:0;//根据检测结果输入 int y=(q!=NULL)?q->val:0; int sum=carry+x+y; carry=sum/10; curr->next=new ListNode(sum%10); curr=curr->next; if(p!=NULL) p=p->next;//检测数据长短 if(q!=NULL) q=q->next; } if(carry>0) { curr->next=new ListNode(carry); } return dummyHead->next; } };
结果:
原本自己想要用递归进行操作,后面发现不行,无法解决数据长短不一或者最高位相加发生进位的情况。
#include<iostream> #include<vector> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode *father):val(x),next(father) {} }; class Solution { public: std::vector<int> tmp = {0}; int i = 0; ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* result=new ListNode(0); tmp.push_back((l1->val + l2->val)/10); std::cout << tmp[i] << std::endl; i++; if (NULL != l1->next && NULL != l2->next) { result->next = addTwoNumbers(l1->next, l2->next); } result->val = (tmp[--i] + l1->val + l2->val) % 10; return result; } }; int main() { Solution solution; ListNode *result; ListNode *a1 = new ListNode(3); ListNode *a2 = new ListNode(2,a1); ListNode *a3 = new ListNode(4,a2); ListNode *b1 = new ListNode(4); ListNode *b2 = new ListNode(3, b1); ListNode *b3 = new ListNode(6, b2); result=solution.addTwoNumbers(a3,b3); system("pause"); return 0; }
相关文章推荐
- leetcode 链表里的两数相加 C++实现
- LeetCode每日一题 009 两数相加
- Leetcode 第二题,两数链表相加
- LeetCode 2. Add Two Numbers(两数相加)
- LeetCode 02. 两数相加(链表) 03.最大不重复的字符串
- leetcode刷题第一天~两数相加
- LeetCode - 两数相加
- Leetcode 653. Two Sum IV - Input is a BST 两数相加4 解题报告
- Leetcode(C++)——2. 两数相加
- 【LeetCode】- Two Sum(两数相加)
- 【LeetCode-2】 两数相加 (链表)
- leetcode 两数相加
- [Leetcode] 2. 两数相加 java
- LeetCode-2 两数相加 Add Two Numbers
- 从零开始刷LeetCode:[2] 两数相加
- [LeetCode] Add Two Numbers 两数相加
- leetcode--两数相加
- leetcode 1 Two sum(两数相加)
- leetcode2:两数相加
- leetcode 两数相加