https://leetcode.com/problems/add-two-numbers/description/
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
We have l1=343, l2=261 when add(l1,l2) we have 3+2=5, 4+6=10 /10=1 1 carry to next,
second digit set to (10%10=0) 0, 3+1=4 but 4 + carry = 5, add(l1,l2) = 505
1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 2 ListNode dummy = new ListNode(0); 3 int sum =0 ; 4 ListNode curr = dummy ; 5 ListNode p1 = l1, p2 = l2 ; 6 while (p1 != null || p2 != null){ 7 if (p1 != null){ 8 sum += p1.val ; 9 p1 = p1.next ; 10 } 11 if (p2 != null){ 12 sum += p2.val ; 13 p2 = p2.next; 14 } 15 curr.next = new ListNode(sum %10) ; //10 %10 =0 16 sum /=10 ; //7/10 =0, 10/10 =1 11/10 =1 17 curr = curr.next ; 18 } 19 /* 642 + 465 20 * if (2 -> 4 -> 6) + (5 -> 6 -> 4) 21 * 2+5 = 7 node:7 22 * 4+ 6 = 10, node: 0 carry 1 23 * 6+4+1 = 11 node: 1 carry 1 === this needs special treatment 24 * 链表连成: 7011 系统自动转换成: 1107 25 * */ 26 //两位数想加 最大进1位 不可能最后成2 27 if (sum == 1){ 28 curr.next = new ListNode(1) ; 29 } 30 return dummy.next ; 31 }