LeetCode 2 - Add Two Numbers
来源:互联网 发布:js遍历json数组对象 编辑:程序博客网 时间:2024/05/16 17:44
问题简述
- 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
我的解答
这是一道很简单的题。
思路很直接,就像笔算加法一样,从最低位开始一位位计算,不过要注意进位的处理。另外,一开始也要初始化两个指针head和tail,前者用来作为最后返回的答案,后者是用来不断修改链表的。
#include <iostream>#include <vector>#include <list>#include <algorithm>#include <cmath>using namespace std;class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int carry=0; ListNode *head=NULL,*tail=NULL; if(l1==NULL&&l2==NULL) { //Nothing } else if(l1==NULL) { head=new ListNode(l2->val); tail=head; l2=l2->next; } else if(l2==NULL) { head=new ListNode(l1->val); tail=head; l1=l1->next; } else { auto sum=l1->val+l2->val; if(sum>=10) { sum-=10; carry=1; head=new ListNode(sum); tail=head; } else { head=new ListNode(sum); tail=head; } l1=l1->next; l2=l2->next; } while (1) { if(l1==NULL&&l2==NULL) { if(carry) tail->next=new ListNode(carry); tail=tail->next; break; } else if(l1==NULL) { auto sum=l2->val+carry; carry=0; if(sum>=10) { carry=1; sum-=10; } tail->next=new ListNode(sum); tail=tail->next; l2=l2->next; } else if(l2==NULL) { auto sum=l1->val+carry; carry=0; if(sum>=10) { carry=1; sum-=10; } tail->next=new ListNode(sum); tail=tail->next; l1=l1->next; } else { auto sum=l1->val+l2->val+carry; carry=0; if(sum>=10) { sum-=10; carry=1; tail->next=new ListNode(sum); tail=tail->next; } else { tail->next=new ListNode(sum); tail=tail->next; } l1=l1->next; l2=l2->next; } } return head; }};
0 0
- LeetCode 2 - Add Two Numbers
- LeetCode 2: Add Two Numbers
- Leetcode: Add Two Numbers (2)
- [leetcode 2] Add Two Numbers
- [Leetcode] 2 - Add Two Numbers
- LeetCode 2:《Add Two Numbers》
- LeetCode | #2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [Leetcode]2Add Two Numbers
- leetcode #2 Add Two Numbers
- leetcode-2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [leetcode] #2 Add Two Numbers
- LeetCode-2 Add Two Numbers
- LeetCode-2-Add Two Numbers
- Leetcode[2] Add Two Numbers
- LeetCode 2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- BZOJ2730: [HNOI2012]矿场搭建 Tarjan求割点
- Jenkins 访问 samba 共享文件夹
- 一些以前学习的Android知识的整理(1)。
- java模版引擎freemarker和velocity的对比
- java.lang.reflect.Array有什么用
- LeetCode 2 - Add Two Numbers
- 匹配“is outside location”
- 用html5 canvas js 实现图片大小的压缩显示,图片上传后可在线预览。
- android Tips
- 将Gif图转换成Unity Texture2D
- HDU Bone Collector II
- SVG实现超酷素描动画
- PyQT实现一个自动生成配置工具
- 浙大PAT甲级 1100