2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. 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.
给定两个非空链表,表示两个非负整数。数字是倒序存储的,每个节点包括一个单独的数字。将这两个数字相加,把结果以链表的形式返回。
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
可以假设这两个数字均不以0开头,除了0本身。
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
这个问题和67. Add Binary比较像~
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1;
ListNode c2 = l2;
ListNode sentinel = new ListNode(0);
ListNode d = sentinel;
int sum = 0;
while (c1 != null || c2 != null) {
sum /= 10;
if (c1 != null) {
sum += c1.val;
c1 = c1.next;
}
if (c2 != null) {
sum += c2.val;
c2 = c2.next;
}
d.next = new ListNode(sum % 10);
d = d.next;
}
if (sum / 10 == 1)
d.next = new ListNode(1);
return sentinel.next;
}
}
我自己的做法,大致和高票答案一样,只是我的把结果链表头单独计算,代码复杂了一点
if(l1==null)
return l2;
if(l2==null)
return l1;
int carry=0;
int sum=0;
ListNode result=new ListNode((l1.val+l2.val)%10);
carry=(l1.val+l2.val)/10;;
l1=l1.next;
l2=l2.next;
ListNode pointer=result;
while(l1!=null||l2!=null)
{
sum=carry;
if(l1!=null)
{
sum=sum+l1.val;
l1=l1.next;
}
if(l2!=null)
{
sum=sum+l2.val;
l2=l2.next;
}
carry=sum/10;
pointer.next=new ListNode(sum%10);
pointer=pointer.next;
}
if (carry!=0)
pointer.next=new ListNode(carry);
return result;