LeetCode-2. Add Two Numbers
来源:互联网 发布:珠宝软件 编辑:程序博客网 时间:2024/06/06 09:09
题目概述:
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
思路:
1、创建一个新链表,并分别使用三个指针指向三个链表,新建一个整型变量来存放进位值;
2、只要分别指向l1和l2的指针p1、p2不为空指针,就将值同之前的进位值相加;
3、所得的和%10赋给p3,所得的和/10来判断下一位是否有进位;
4、最后如果p1和p2都为空,但仍有进位,则新建一个节点保存进位值。
注意:p1=p1->next;p2=p2->next;操作前要先判断是否为空指针。
/** * 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) { ListNode* dummy=new ListNode(0); ListNode* p1=l1; ListNode* p2=l2; ListNode* p3=dummy; int carry=0; while(p1!=nullptr||p2!=nullptr) { int p1_val=(p1==nullptr)?0:p1->val; int p2_val=(p2==nullptr)?0:p2->val; p3->val=(p1_val+p2_val+carry)%10; if((p1_val+p2_val+carry)/10==1) carry=1; else carry=0; if(p1!=nullptr) p1=p1->next; if(p2!=nullptr) p2=p2->next; if(p1!=nullptr||p2!=nullptr||carry!=0) { p3->next=new ListNode(carry); p3=p3->next; } } return dummy; }};
/** * 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) { ListNode *head=new ListNode(0); ListNode *ptr=head; int carry=0; while(true){ if(l1!=NULL) { carry+=l1->val; l1=l1->next; } if(l2!=NULL) { carry+=l2->val; l2=l2->next; } ptr->val=carry%10; carry=carry/10; if(l1!=NULL||l2!=NULL||carry!=0) { ptr->next=new ListNode(0); ptr=ptr->next; } else break; } return head; }};
这里的更详细,思路更清晰:https://leetcode.com/problems/add-two-numbers/solution/
阅读全文
0 0
- [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
- LeetCode - 2. Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode 2. Add Two Numbers
- Leetcode 2. Add Two Numbers
- 2. Add Two Numbers LeetCode
- leetcode 2. Add Two Numbers
- LeetCode-2. Add Two Numbers
- LeetCode 2. Add Two Numbers
- 2. Add Two Numbers----LeetCode
- EF从数据库更新Module
- 源码浅析 ArrayList、Vector、LinkedList 的区别
- 机器学习实战【9】(岭回归和Lasso)
- 微信调用jssdk在网页端实现调用扫一扫,java+jsp
- 求素数的C语言代码优化
- LeetCode-2. Add Two Numbers
- 花生壳内网穿透-ssh远程
- 关于java后台处理base64数据
- 变量的声明和定义
- Android+Json+SSM+MySQL后台数据交互模拟云备份云恢复(源码)
- PullToRefreshListView,上拉加载更多时,数据加20条。。。。。。下拉加载更多时,数据加0条,
- HttpUrlConnection的setDoOutput与setDoInput的区别
- MapReduce shuffle过程剖析及调优
- 论文笔记:Single-Image Crowd Counting via Multi-Column Convolutional Neural Network