【Shawn-LeetCode】2.Add Two Numbers
来源:互联网 发布:做网络直播需要什么设备 编辑:程序博客网 时间:2024/05/23 01:18
2.Add Two Numbers
Question:
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
Subscribe to see which companies asked this question.
解析:
如果使用C语言做的话,可以用next指针进行处理,效率确实会高,Java理解起来就有点困难了。首先明确这种题用递归无疑是最快的,建立临时结构体curr来保存和的个位,curr的next指向下一位,并把进位传递过去,并不一定要向题目中说的要进行倒置保存。
第二点要考虑情况,l1比l2长,相等,短三种情况,长或者短,为其中一个添加一个新的节点,并参与运算,如果相等,则判断进位是否为空,为空则结束,不为空则将进位置为第一位,以下为源代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { return helper(l1,l2,0); } public ListNode helper(ListNode l1, ListNode l2, int carry){ if(l1==null && l2==null){ return carry == 0? null : new ListNode(carry); } if(l1==null && l2!=null){ l1 = new ListNode(0); } if(l2==null && l1!=null){ l2 = new ListNode(0); } int sum = l1.val + l2.val + carry; ListNode curr = new ListNode(sum % 10); curr.next = helper(l1.next, l2.next, sum / 10); return curr; }}
阅读全文
0 0
- 【Shawn-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
- 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
- 使用定位获取当前位置信息
- 在Java中super和this的区别
- Heidi and Library (medium)
- java中,一个类实现某个接口,必须重写接口中的所有方法吗???
- python exec 和 eval 函数的用法
- 【Shawn-LeetCode】2.Add Two Numbers
- Windows下安装Tensorflow
- 端口占用解决方案
- React Native Application和Activity源码分析
- 问题求解,关于java随机生成指定长度的字符串
- 学习使用express
- 【2017年上海金马五校程序设计竞赛】C : Count the Number 【DFS】
- linux下dos界面的方块窗口模块
- 矩阵中的路径dfs