[LeetCode]Add Two Numbers
Add Two Numbers
相加兩個非負整數的鏈表,計算加總後的數字。
Example 1
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.
Example 2
Input: l1 = [0], l2 = [0] Output: [0]Example 3
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]
解法
PHP
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution {
/**
* @param ListNode $l1
* @param ListNode $l2
* @return ListNode
*/
function addTwoNumbers($l1, $l2) {
$sum = 0;
$carry = 0;
$arr_sum = [];
while ($l1 != '' || $l2 != '') {
$sum = $l1->val + $l2->val + $carry;
if ($sum >= 10) {
$carry = intval($sum / 10);
$sum = $sum % 10;
} else {
$carry = 0;
}
$arr_sum[] = $sum;
$l1 = $l1->next;
$l2 = $l2->next;
}
if ($carry > 0)
$arr_sum[] = $carry;
$result_list = new ListNode();
$res = $result_list;
foreach ($arr_sum as $num) {
$res->next = new ListNode($num);
$res = $res->next;
}
return $result_list->next;
}
}
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1, l2):
sum = 0
carry = 0
arr_sum = []
while l1 or l2:
val_1 = val_2 = 0
if l1:
val_1 = l1.val
l1 = l1.next
if l2:
val_2 = l2.val
l2 = l2.next
sum = val_1 + val_2 + carry
carry = 0
if sum >= 10:
carry = int(sum / 10)
sum %= 10
arr_sum.append(sum)
if carry > 0:
arr_sum.append(carry)
result_list = ListNode()
res = result_list
for num in arr_sum:
res.next = ListNode(num)
res = res.next
return result_list.next
留言
張貼留言