Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
难点
1、ListNode的操作。
2、考虑进位的问题。
3、这道题由于数字反序,所以实际上从首位开始相加正好符合笔算时候的顺序。
解法
public class ListNode {
int val;
ListNode next;
ListNode(int x){
this.val = x;
}
}
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = l1;
ListNode q = l2;
ListNode head = new ListNode(0);
ListNode curr = head;
int sum =0;
while(p != null || q != null){
sum = sum / 10;
if(p != null){
sum += p.val;
p = p.next;
}
if(q != null){
sum += q.val;
q = q.next;
}
curr.next = new ListNode(sum % 10);
curr = curr.next;
}
if(sum >= 10){
curr.next = new ListNode(1);
}
return head.next;
}
}