题目描述:
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Subscribe to see which companies asked this question.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode fake = new ListNode(0);
ListNode t=fake, t1=l1, t2=l2;
int a1, a2, r = 0;
while (t1!=null || t2!=null || r!=0) {
a1 = t1==null ? 0:t1.val;
a2 = t2==null ? 0:t2.val;
r += a1 + a2;
t.next = new ListNode(r%10);
r /= 10;
t = t.next;
if (t1!=null) t1 = t1.next;
if (t2!=null) t2 = t2.next;
}
return fake.next;
}