class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode();
boolean carry = false;
ListNode pointerL1 = l1, pointerL2 = l2,
resultPointer = result;
while (pointerL1 != null && pointerL2 != null) {
int sum = pointerL1.val + pointerL2.val;
if (carry) {
sum += 1;
carry = false;
}
if (sum >= 10) {
carry = true;
sum = sum % 10;
}
resultPointer.val = sum;
pointerL1 = pointerL1.next;
pointerL2 = pointerL2.next;
if (pointerL1 != null || pointerL2 != null || carry) {
resultPointer.next = new ListNode();
}
resultPointer = resultPointer.next;
}
while (pointerL1 != null) {
int sum = pointerL1.val;
if (carry) {
sum += 1;
carry = false;
}
if (sum >= 10) {
carry = true;
sum = sum % 10;
}
resultPointer.val = sum;
pointerL1 = pointerL1.next;
if (pointerL1 != null || carry) {
resultPointer.next = new ListNode();
}
resultPointer = resultPointer.next;
}
while (pointerL2 != null) {
int sum = pointerL2.val;
if (carry) {
sum += 1;
carry = false;
}
if (sum >= 10) {
carry = true;
sum = sum % 10;
}
resultPointer.val = sum;
pointerL2 = pointerL2.next;
if (pointerL2 != null || carry) {
resultPointer.next = new ListNode();
}
resultPointer = resultPointer.next;
}
if (carry) {
resultPointer.val = 1;
}
return result;
}
}
No comments:
Post a Comment