2. Add Two Numbers #33
-
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 contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps: Let's implement this solution in PHP: 2. Add Two Numbers <?php
// Helper function to create a linked list from an array
function createLinkedList($arr) {
$dummyHead = new ListNode(0);
$current = $dummyHead;
foreach ($arr as $val) {
$current->next = new ListNode($val);
$current = $current->next;
}
return $dummyHead->next;
}
// Helper function to convert linked list to array (for easy verification)
function linkedListToArray($node) {
$arr = [];
while ($node !== null) {
$arr[] = $node->val;
$node = $node->next;
}
return $arr;
}
// Example usage:
$l1 = createLinkedList([2, 4, 3]);
$l2 = createLinkedList([5, 6, 4]);
$result = addTwoNumbers($l1, $l2);
print_r(linkedListToArray($result)); // Output: [7, 0, 8]
$l1 = createLinkedList([0]);
$l2 = createLinkedList([0]);
$result = addTwoNumbers($l1, $l2);
print_r(linkedListToArray($result)); // Output: [0]
$l1 = createLinkedList([9, 9, 9, 9, 9, 9, 9]);
$l2 = createLinkedList([9, 9, 9, 9]);
$result = addTwoNumbers($l1, $l2);
print_r(linkedListToArray($result)); // Output: [8, 9, 9, 9, 0, 0, 0, 1]
?> Explanation:
This solution correctly handles the addition of two numbers represented as linked lists, considering edge cases and ensuring the result is also in linked list format. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 2. Add Two Numbers