[LeetCode]--Add Two Numbers
来源:互联网 发布:淘宝店铺等级 编辑:程序博客网 时间:2024/05/16 14:15
题目
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
分析
因为数字按照逆序存储,显然题中所给的示例中两数分别为:342,465。而342+465=807。因此最终返回数807的逆向存储列表7->0->8。
刚开始在写这道题的时候,想当然地认为两个链表的长度相同。而这恰恰是我们思维的一个误区。题中并没有提及两链表的长度,因此有可能是不同的,这就需要事先判断指针是否指向null,即链表是否将为空,若为空则建立一个新的存储数字“0”的节点。
解决了这个问题,这道题就很容易Pass了。我们先建立一个新列表result(将结果存储在其中),然后遍历两个给出列表中的对应节点并做加法运算。值得注意的是,两数相加若大于10,我们将利用取模(%)运算得到本位结果,利用除法(/)运算得到进位结果保存在carry中并在下一位的加法运算过程中加上carry。如果两链表的所有非空节点都已遍历完,且carry>0时,则需要新创建一个节点以保存运算结果的最高位。
解答
/** * 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* m=l1; ListNode* n=l2; ListNode* result=new ListNode(0); ListNode* cur=result; int carry=0; int sum=0; while(m!=NULL || n!=NULL){ if(m==NULL) { m=new ListNode(0); } if(n==NULL) { n=new ListNode(0); } sum=(m->val)+(n->val)+carry; carry=sum/10; //cout<<carry<<" "<<sum<<endl; cur->next=new ListNode(sum%10); cur=cur->next; if(m!=NULL) m=m->next; if(n!=NULL) n=n->next; sum=0; } if(carry>0){ cur->next=new ListNode(carry); } return result->next; }};
不难得出,该算法的复杂度为O(max{l1.size(), l2.size()})
阅读全文
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
- Java中的Object类详细介绍
- 通过接口解决多线程下的数据同步问题
- QuartZ Cron表达式
- mysql函数之统计一个字符在字符串中出现的次数 。
- poj 3294 Life Forms(n个字符串中 求公共子串长度超过k得最大子串 后缀数组)
- [LeetCode]--Add Two Numbers
- 如何提取坡度大于15°的数据(2)
- 文章标题是tabLayout_viewper
- robot framework环境搭建
- java快速寻找一个数组的最大值或最小值, min, max,三种方法
- [LintCode 98] 链表排序(Python)
- UOJ NOIP2015 斗地主 [搜索]
- Spring事务管理
- Android用Okhttp搭建自己的网络框架