LC 02
public class TwoSum02 {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int next1 = 0;
ListNode result = new ListNode(0);
ListNode current = result;
while (l1 != null || l2 != null || next1 != 0) {
int i1 = l1 != null ? l1.val : 0;
int i2 = l2 != null ? l2.val : 0;
int total = i1 + i2 + next1;
next1 = total >= 10 ? 1 : 0;
total = total >= 10 ? total - 10 : total;
current.next = new ListNode(total);
current = current.next;
if (l1 != null)
l1 = l1.next;
if (l2 != null)
l2 = l2.next;
}
return result.next;
}
public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
ListNode resNode = new ListNode(0);
ListNode currNode = resNode;
int carry = 0;
int l1Val;
int l2Val;
int temp;
while (l1 != null || l2 != null || carry > 0) {
l1Val = l1 == null ? 0 : l1.val;
l2Val = l2 == null ? 0 : l2.val;
temp = l1Val + l2Val + carry;
carry = temp / 10;
currNode.next = new ListNode(temp % 10);
currNode = currNode.next;
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
}
return resNode.next;
}
}