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.
思路:首先確定加和的順序,其次邑闲,考慮進位時说敏,用上一位的余數給下一位加上舞箍,同時考慮二者一長一短的問題曲横。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null || l2 == null){
return null;
}
ListNode p3 = new ListNode(0);
int value1 = 0, value2 = 0;
ListNode result = p3;
while(l1 != null && l2 != null){
value2 = (l1.val + l2.val + value1) % 10;
value1 = (l1.val + l2.val + value1) / 10;
p3.next = new ListNode(value2);
l1 = l1.next;
l2 = l2.next;
p3 = p3.next;
if(l1 == null && l2 == null){
break;
}else if(l1 == null){
l1 = new ListNode(0);
}else if(l2 == null){
l2 = new ListNode(0);
}
}
if(value1 != 0){
p3.next = new ListNode(value1);
}
return result.next;
}
}