[LeetCode][Java] Add Two Numbers
2015-07-05 21:01
393 查看
题目:
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
题意:
给定两个链表,分别代表两组非负数字。这些数字在链表中按反序存储,例如342在链表中为2->4->3。链表每一个节点包含一个数(0-9)。计算这两个数字和并以链表形式返回。算法分析:
链表中若两个数(temp1和temp2)相加,需要考虑原来的数相加带来的进位(addnum)。将两个数相加的结果放在新的链表中,最后返回这个新的链表就好。代码如下:
/** * 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) { int addnum=0; ListNode next_l1 = l1; ListNode next_l2 = l2; ListNode newHead = new ListNode(0); ListNode p3 = newHead; while(next_l1!=null||next_l2!=null ) { int temp1=0; int temp2=0; int temp3=0; int temp4=0; int temp5=0; if (next_l1!=null) { temp1=next_l1.val; next_l1=next_l1.next; } if (next_l2!=null) { temp2=next_l2.val; next_l2=next_l2.next; } temp3=temp1+temp2+addnum; if (temp3>=10) { temp4 = temp3/10;//进位数 temp5 = temp3%10;//新的和 p3.next = new ListNode(temp5); addnum = temp4; if (next_l1==null && next_l2==null ) p3.next.next = new ListNode(temp4); } else { p3.next = new ListNode(temp3); addnum=0; } p3=p3.next; } return newHead.next; } }
相关文章推荐
- 关于mac版eclipse的配置问题
- javaSE学习笔记之反射
- Eclipse关闭检查
- java 错误:由于文件名不对所造成
- eclipse 远程调试mapreduce
- [LeetCode][Java] Two Sum
- 一种JAVA线程轮训调度算法(转载)
- java基础------抽象类和接口
- Java堆排序(HeapSort)算法实现
- Struts2框架学习(三) 数据处理
- Struts2框架学习(二) Action
- Struts2框架学习(一)
- spring框架学习(六)AOP
- spring框架学习(五)注解
- spring框架学习(四)自动装配
- Eclipse下搭建Corba开发环境+HelloWorld实现过程
- spring框架学习(三)junit单元测试
- java中的内部类和Lambda表达式
- spring框架学习(二)依赖注入
- java死锁程序