2. Add Two Numbers
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 1:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
第一次(自己二刷):
/**
* 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) {
ListNode result = new ListNode(-1);
ListNode temp = result;
int carry = 0;
while (l1 != null || l2 != null) {
int sum = 0;
if (l1 == null) {
sum = l2.val + carry;
l2 = l2.next;
} else if (l2 == null) {
sum = l1.val + carry;
l1 = l1.next;
} else {
sum = l2.val + l1.val + carry;
l1 = l1.next;
l2 = l2.next;
}
carry = sum >= 10 ? 1 : 0;
temp.next = new ListNode(sum % 10);
temp = temp.next;
}
if (carry == 1) {
temp.next = new ListNode(1);
temp = temp.next;
}
temp.next = null;
return result.next;
}
}
看答案后(思路一样,更加简洁):
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode result = head;
int carry = 0;
while (l1 != null || l2 != null || carry > 0) {
int resVal = (l1 != null? l1.val : 0) + (l2 != null? l2.val : 0) + carry;
result.next = new ListNode(resVal % 10);
carry = resVal / 10;
l1 = (l1 == null ? l1 : l1.next);
l2 = (l2 == null ? l2 : l2.next);
result = result.next;
}
return head.next;
}