您的位置:首页 > Web前端 > Node.js

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ListNode leetcode