Medium 445题 Add Two Numbers II
来源:互联网 发布:淘宝手淘搜索怎么增加 编辑:程序博客网 时间:2024/06/07 14:31
Question:
You are given two linked lists representing two non-negative numbers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Solution:
/** * 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) { List<Integer> n1=new ArrayList<Integer>(); while(l1!=null) { int tmp=l1.val; n1.add(tmp); l1=l1.next; } List<Integer> n2=new ArrayList<Integer>(); while(l2!=null) { int tmp=l2.val; n2.add(tmp); l2=l2.next; } ListNode head=new ListNode(0); ListNode post=null; int carry=0; int i=n1.size()-1; int j=n2.size()-1; for(;i>=0||j>=0||carry!=0;i--,j--){ int cur=0; if(i>=0) cur+=n1.get(i); if(j>=0) cur+=n2.get(j); cur+=carry; carry=cur/10; post=head.next; ListNode tmp=new ListNode(cur%10); head.next=tmp; tmp.next=post; } return head.next; }}
0 0
- Medium 445题 Add Two Numbers II
- Add Two Numbers [Medium]
- Add Two Numbers(medium)
- [Medium]Add Two Numbers
- Medium 2题 Add Two Numbers
- 445-Add Two Numbers II
- LeetCode解题报告 445. Add Two Numbers II [medium]
- Leetcode 445. Add Two Numbers II (Medium) (cpp)
- 2. Add Two Numbers Medium
- Add Two Numbers II
- Add Two Numbers II
- Add Two Numbers II
- Add Two Numbers II
- Leetcode Add Two Numbers II 445
- leetcode 445 Add Two Numbers II C++
- LeetCode #445: Add Two Numbers II
- Leetcode#445(链表)-Add Two Numbers II
- 【leetcode 445】Add Two Numbers II
- mac linux rename命令行批量修改文件名
- 对协变和逆变的理解(Contravariance and Covariance)
- c++学习笔记--拷贝构造函数
- Atitit vod ver 12 new feature v12 pb2 影吧 视频 电影 点播 播放系统v12新特性
- HDU 2457 DNA repair AC自动机+DP
- Medium 445题 Add Two Numbers II
- 浅析NSTimer & CADisplayLink内存泄露
- 免安装版MySQL(绿色版)配置过程及安装过程中可能出现的问题详解
- HTTP 状态返回码
- masterJ2EE篇003——Tomcat 7.0配置文件部署项目
- mybatis多表之间的查询resultMap
- lightoj 1031 被区间dp虐哭...看题解才学会
- 谷歌中国算法比赛解题报告 APAC2014A
- 性能优化之NSDateFormatter