Add Two Numbers Medium
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
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
int carry = 0, val = 0;
while (l1 != null || l2 != null) {
val = carry;
if (l1 != null) {
val += l1.val;
l1 = l1.next;
}
if (l2 != null) {
val += l2.val;
l2 = l2.next;
}
carry = val / 10;
val = val % 10;
cur.next = new ListNode(val);
cur = cur.next;
}
if (carry > 0) {
cur.next = new ListNode(carry);
}
return dummy.next;
}
思路:数字进位问题,该位有效值为值%10,进位值为值/10。可以使用一个变量记录进位值。