Add Two Numbersjava
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
int carry = 0;
ListNode curr = new ListNode(0);
ListNode dummy = curr;
while (l1 != null && l2 != null) {
curr.next = new ListNode((l1.val + l2.val + carry) % 10);
carry = (l1.val + l2.val + carry) / 10;
curr = curr.next;
l1 = l1.next;
l2 = l2.next;
}
while (l1 == null && l2 != null) {
curr.next = new ListNode((l2.val + carry) % 10);
carry = (l2.val + carry) / 10;
curr = curr.next;
l2 = l2.next;
}
while (l2 == null && l1 != null) {
curr.next = new ListNode((l1.val + carry) % 10);
carry = (l1.val + carry) / 10;
curr = curr.next;
l1 = l1.next;
}
if (carry != 0) {
curr.next = new ListNode(carry);
}
return dummy.next;
}
}
複製代碼
//優化while循環
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
int carry = 0;
ListNode head = new ListNode(0);
ListNode dummy = head;
while (l1 != null || l2 != null) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
head.next = new ListNode(sum % 10);
head = head.next;
carry = sum / 10;
}
if (carry != 0) {
head.next = new ListNode(carry);
}
return dummy.next;
}
}
複製代碼
445. Add Two Numbers II優化