leetcode-Add Two Numbers
来源:互联网 发布:淘宝客户端官方下载 编辑:程序博客网 时间:2024/05/16 15:45
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
题意:用链表模拟高精度加法。给出两个链表,分别逆序存储了两个数,即表头是个位上的数,第二节点是十位上的数……对其求和,结果以同样形式表示
分析:比较简单的链表操作题,每次遍历每个节点,计算每位上的和,记录进位,然后加入到新链表即可
注意:
1、addNode子函数是更新指针本身的值,所以参数要传递指针的引用
2、若两个链表长度不等,遍历完公共部分后要遍历较长的链表
3、最后若还有进位,要把进位加入结果链表
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: void addNode(ListNode *&head, ListNode *&tail, ListNode *&now) { if(!head) { head = tail = now; } else { tail->next = now; tail = now; } } ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode *head=NULL,*tail=NULL,*now; ListNode *t1=l1,*t2=l2; int carry = 0; for(; t1&&t2; t1=t1->next,t2=t2->next) { int value = t1->val+t2->val+carry; carry = value/10; value %= 10; now = new ListNode(value); addNode(head,tail,now); } for(; t1; t1=t1->next) { int value = t1->val+carry; carry = value/10; value %= 10; now = new ListNode(value); addNode(head,tail,now); } for(; t2; t2=t2->next) { int value = t2->val+carry; carry = value/10; value %= 10; now = new ListNode(value); addNode(head,tail,now); } if(carry) { now = new ListNode(carry); addNode(head,tail,now); } return head; }};
0 0
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode - Add Two Numbers
- LeetCode | Add Two Numbers
- 【leetcode】Add Two Numbers
- swing中弹出提示框
- 有经验的同学或从事java开发的给些经验。
- cocos2dx 常见的49中动作详解
- 烦 烦 烦
- 搞搞文艺范儿
- leetcode-Add Two Numbers
- 青春——人生的苦茶
- samba配置
- 素数距离问题
- Android Support v4、v7、v13的区别和应用场景
- 【WebApp】webApp开发总结(集合贴)
- java ArrayBlockingQueue 使用示例
- EBS 不能打开MES Supervisor 职责
- 在Javascript删除列表项中的下拉项怎么弄