问题:
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
解决方案:
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode node=null;
node=new ListNode(0);
ListNode l=node;
int c=0;
while(true)
{
node.val=(l1.val+l2.val+c)%10;
c=(l1.val+l2.val+c)/10;
if(l1.next==null&&l2.next==null)
{
if(c==1)
{
node.next=new ListNode(1);
node=node.next;
}
break;
}
node.next=new ListNode(0);
node=node.next;
if((l1=l1.next)==null) l1=new ListNode(0);
if((l2=l2.next)==null) l2=new ListNode(0);
}
return l;
}
}
解法相对简单,适合初学者。