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

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