LeetCode2:Add Two Numbers
2015-06-05 20:57
375 查看
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
注意对象的引用传递过程。写得有些复杂.......
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
注意对象的引用传递过程。写得有些复杂.......
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode tai; int carry=0; int temp1=l1.val+l2.val; if(temp1>=10){ temp1=temp1%10; carry=1; } ListNode ans=new ListNode(temp1); ListNode currentans=ans; //ans.next=currentans; while((l1=l1.next)!=null&&(l2=l2.next)!=null){ int temp=l1.val+l2.val+carry; if(temp>=10){ temp=temp%10; carry=1; }else{ carry=0; } currentans.next=new ListNode(temp); currentans=currentans.next; } if(l1==null&&l2!=null){ l2=l2.next; } while(l1!=null){ int temp=l1.val+carry; if(temp>=10){ temp=temp%10; carry=1; }else{ carry=0; } currentans.next=new ListNode(temp); currentans=currentans.next; l1=l1.next; } while(l2!=null){ int temp=l2.val+carry; if(temp>=10){ temp=temp%10; carry=1; }else{ carry=0; } currentans.next=new ListNode(temp); currentans=currentans.next; l2=l2.next; } if(carry==1){ currentans.next=new ListNode(1); currentans=currentans.next; } return ans; } }
相关文章推荐
- Android学习日记(1)
- 中缀式转化为前缀式,中缀式转化为后缀式
- 【矩阵乘】【NOI 2012】【cogs963】随机数生成器
- SAE开发 大小写问题
- 5.给出设计类图
- X-UA-Compatible
- SVG基础——如何使用可缩放矢量图形(SVG)
- 第十四周项目 小玩文件
- HDU 不容易系列之一
- 多wan示意图
- 黑马程序员-关于生产者消费者和火车票出售的线程问题
- 黑马程序员——Java基础——异常
- H.264/ACC音视频编码流的RTP/RTSP传输实现(3)
- ubuntu下python opencv搭建
- HDU 献给杭电五十周年校庆的礼物
- Linux 目录流管理
- Java间隔计时触发器
- MATLAB产生的导频经QPSK调制后的精度的问题
- C#分割字符串split()方法
- Mybatis-spring整合源码解析