【LeetCode】2. Add Two Numbers 解題報告
阿新 • • 發佈:2019-01-08
Subject
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explain
有兩個連結串列,它們表示逆序的兩個非負數。計算出兩個數的和之後,同樣逆序輸出作為一個連結串列。
需要注意一點:有進位
Solution
solution 1
便利兩個連結串列,以此相加,把進位的數字計入下一組相加的數字中。
需要注意一種情況,比如{5} , {5}兩個列表,輸出的結果應該是{0, 1}。
/**
* 57ms <br />
* 將個數較少的列表後面補上0
*
* @param l1
* @param l2
* @return
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return null;
}
ListNode temp = new ListNode(0);
ListNode result = temp;
int value1 = 0;
int value2 = 0;
while (l1 != null && l2 != null ) {
value2 = (l1.val + l2.val + value1) % 10;
value1 = (l1.val + l2.val + value1) / 10;
temp.next = new ListNode(value2);
l1 = l1.next;
l2 = l2.next;
temp = temp.next;
if (l1 == null && l2 == null) {
break;
}
if (l1 == null) {
l1 = new ListNode(0);
}
if (l2 == null) {
l2 = new ListNode(0);
}
}
if (value1 != 0) {
temp.next = new ListNode(value1);
}
return result.next;
}
solution 2
遞迴方式。
/**
* 遞迴方式 -- 56ms
*
* @param l1
* @param l2
* @return
*/
public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return l1 == null ? l2 : l1;
}
int value = l1.val + l2.val;
ListNode result = new ListNode(value % 10);
result.next = addTwoNumbers2(l1.next, l2.next);
if (value >= 10) {
result.next = addTwoNumbers2(new ListNode(value / 10), result.next);
}
return result;
}
solution 3
摘自『九章演算法』的答案。
將過程分為三種情況。現將兩個連結串列等長度對應的數字之和計算出來,然後兩個連結串列有一個為空了。此時分兩種情況(類似情況)。如果l1不為空,則將l1連結串列的值與“進位”相加再取餘做為下一個結果元素的值。
/**
* 九章演算法答案 <br />
* http://www.jiuzhang.com/solutions/add-two-numbers/
*
* @param l1
* @param l2
* @return
*/
public ListNode addTwoNumbers3(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
ListNode head = new ListNode(0);
ListNode point = head;
int carry = 0;
while (l1 != null && l2 != null) {
int sum = carry + l1.val + l2.val;
point.next = new ListNode(sum % 10);
carry = sum / 10;
l1 = l1.next;
l2 = l2.next;
point = point.next;
}
while (l1 != null) {
int sum = carry + l1.val;
point.next = new ListNode(sum % 10);
carry = sum / 10;
l1 = l1.next;
point = point.next;
}
while (l2 != null) {
int sum = carry + l2.val;
point.next = new ListNode(sum % 10);
carry = sum / 10;
l2 = l2.next;
point = point.next;
}
if (carry != 0) {
point.next = new ListNode(carry);
}
return head.next;
}
bingo~~