leetCode两数之和
2018-03-25 16:39
183 查看
/** * 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 res(0),*rus=&res; int tmp=0;//用来储存有可能的进位 while(l1 or l2 or tmp){ int sum=(l1 ? l1->val : 0)+(l2 ? l2->val : 0)+ tmp;//求出每位的数,并且判断l1和l2 tmp=sum/10;//判断是否有进位 rus->next=new ListNode(sum%10);//存储结果 rus=rus->next; l1=l1 ? l1->next : l1;//判断l1是否为空,不为空则进入下一个 l2=l2 ? l2->next : l2;//判断l2是否为空,不为空则进入下一个 } return res.next; } };
相关文章推荐
- 【LeetCode】【数组】【简单】【两数之和】
- LeetCode - 1. 两数之和
- LeetCode 1. Two Sum (两数之和)
- [leetcode, python] Two Sum 两数之和等于某数
- LeetCode-Two Sum(两数之和)
- LeetCode | 两数之和除以10
- [LeetCode] Divide Two Integers 两数相除
- [LeetCode] Sum of Two Integers 两数之和
- 从零打卡leetcode之day 1--两数之和
- LeetCode - 167. 两数之和 II - 输入有序数组
- [leetcode, python] Two Sum 两数之和等于某数
- 167.leetcode Two Sum II - Input array is sorted(medium)[两数求和固定值]
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- [LeetCode] Two Sum II - Input array is sorted 两数之和之二 - 输入数组有序
- LeetCode | 两数之和
- [Leetcode] Add two numbers 两数之和
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- 从零打卡leetcode之day 2---两数相加
- [leetcode, python] Two Sum 两数之和等于某数
- LeetCode - 66/67 - 两数相加加法模拟