您的位置:首页 > 编程语言 > Java开发

leetCode练习(2)

2016-09-11 17:58 260 查看
题目:Add Two Numbers           

难度:medium         

问题描述:

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
错误点:分别计算出l1和l2代表的int值再相加,这是错误解法,因为int会溢出。
解题思路:每位相加注意进位即可。代码如下:

public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head,tail,temp,t1,t2;
int x,jinwei=0;
t1=l1;t2=l2;

tail=new ListNode(0);
head=new ListNode(0);

if(t1==null) t1=new ListNode(0);
if(t2==null) t2=new ListNode(0);

//对第一个节点进行初始化
x=t1.val+t2.val+jinwei;
if(x<10){
jinwei=0;
}else{
x=x-10;
jinwei=1;
}
head=new ListNode(x);
tail=head;
t1=t1.next;
t2=t2.next;

//l1,l2尾指针归位
while(true){
if(t1==null&&t2==null&&jinwei==0){
return head;
}else{
if(t1==null) t1=new ListNode(0);
if(t2==null) t2=new ListNode(0);
x=t1.val+t2.val+jinwei;

if(x<10){
jinwei=0;
}else{
x=x-10;
jinwei=1;
}
temp=new ListNode(x);
tail.next=temp;
tail=tail.next;

t1=t1.next;
t2=t2.next;
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode linkedList