Leetcode_Add Two Numbers
2015-04-26 13:51
447 查看
Add Two Numbers
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
已下是java实现:
1、已知下列ListNode的数据结构
public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }2、方法如下:
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int add = 0;//存储进位
int res = 0;//存储每一位相加的结果
ListNode ln = new ListNode(0);
ListNode key = ln;//key是当前节点
while(l1!=null && l2!=null){//处理l1、l2都不为空的情况
res = l1.val+l2.val+add;
if(res>9){
add=1;
res=res-10;
}
else{
add=0;
}
ListNode temp = new ListNode(res);
key.next=temp;
key=temp;
l1=l1.next;
l2=l2.next;
}
if(l1!=null){//处理只剩l1的情况
while(l1!=null){
res = l1.val+add;
if(res>9){
add=1;
res=res-10;
}
else{
add=0;
}
ListNode temp = new ListNode(res);
key.next=temp;
key=temp;
l1=l1.next;
}
}
else if(l2!=null){//处理只剩l2的情况
while(l2!=null){
res = l2.val+add;
if(res>9){
add=1;
res=res-10;
}
else{
add=0;
}
ListNode temp = new ListNode(res);
key.next=temp;
key=temp;
l2=l2.next;
}
}
if(add==1){//处理最后一位有进位的情况
ListNode temp = new ListNode(1);
key.next=temp;
key=temp;
}
return ln.next;
}
3、写一个测试主方法
public static void main(String[] args) { ListNode l1 = new ListNode(2) ; l1.next=new ListNode(8); ListNode l2 = new ListNode(5) ; l2.next=new ListNode(9); l2.next.next=new ListNode(9); ListNode ln =addTwoNumbers(l1,l2); while(ln!=null) { System.out.println(ln.val+"------"); ln=ln.next; } }
4、相当于
Input: (2
-> 8) + (5 -> 9 -> 9)
Output: 7 -> 7 -> 0-
> 1
相关文章推荐
- LeetCode 面试:Add Two Numbers
- LCP002 LeetCode 2. Add Two Numbers
- leetcode-【中等题】2. Add Two Numbers
- C实现 LeetCode->Add Two Numbers
- leetcode——Add Two Numbers
- Leetcode-Add Two Numbers
- LeetCode | Add Two Numbers
- LeetCode Add Two Numbers C++
- leetcode Add Two Numbers
- 【LeetCode002-003算法/编程练习C++】---Add Two Numbers||寻找最长无重复字母子串。//第三题之后有空要再想一想…
- LeetCode Add Two Numbers
- Leetcode – Add Two Numbers (Java)
- leetcode 刷题题解(c++) 2.Add Two Numbers (链表)
- leetcode problem solve 2——Add Two Numbers
- leetcode 2. Add Two Numbers
- LeetCode(2) Add Two Numbers
- 【Leetcode】Add Two Numbers
- Leetcode:2. Add Two Numbers
- LeetCode2:Add Two Numbers
- LeetCode之Add Two Numbers