Status message

Maintenant, vous regardez: 2. Add Two Numbers

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)
  2. Output: 7 -> 0 -> 8
  3. Explanation: 342 + 465 = 807.

Structure:

  1. /**
  2.  * Definition for a singly-linked list.
  3.  * class ListNode {
  4.  * public $val = 0;
  5.  * public $next = null;
  6.  * function __construct($val) { $this->val = $val; }
  7.  * }
  8.  */
  9. class Solution {
  10.  
  11. /**
  12.   * @param ListNode $l1
  13.   * @param ListNode $l2
  14.   * @return ListNode
  15.   */
  16. function addTwoNumbers($l1, $l2) {
  17.  
  18. }
  19. }

Solution1:

  1. /**
  2.  * Definition for a singly-linked list.
  3.  * class ListNode {
  4.  * public $val = 0;
  5.  * public $next = null;
  6.  * function __construct($val) { $this->val = $val; }
  7.  * }
  8.  */
  9. class Solution {
  10.  
  11. /**
  12.   * @param ListNode $l1
  13.   * @param ListNode $l2
  14.   * @return ListNode
  15.   */
  16. function addTwoNumbers($l1, $l2) {
  17. $add_flag = 0;
  18. $result_list = null;
  19.  
  20. do {
  21. $val = $l1->val + $l2->val + $add_flag;
  22. if ($val >= 10) {
  23. $add_flag = 1;
  24. $val -= 10; //减去,因为进位了
  25. } else {
  26. $add_flag = 0;
  27. }
  28.  
  29. $tmp_list = new ListNode($val);
  30. if (is_null($result_list)){
  31. $result_list = $tmp_list;
  32. } else{
  33. $current_node = $result_list;
  34. while ($current_node->next !== null) {
  35. $current_node = $current_node->next;
  36. }
  37. $current_node->next = $tmp_list;
  38. // $next->next = $tmp_list; //?
  39. }
  40. // $next = $tmp_list; //?
  41.  
  42. $l1 = $l1->next;
  43. $l2 = $l2->next;
  44. } while ($l1 || $l2 || $add_flag);
  45.  
  46. return $result_list;
  47. }
  48. }

Solution2:

  1. /**
  2.  * Definition for a singly-linked list.
  3.  * class ListNode {
  4.  * public $val = 0;
  5.  * public $next = null;
  6.  * function __construct($val) { $this->val = $val; }
  7.  * }
  8.  */
  9. class Solution {
  10.  
  11. private $res=0;
  12.  
  13. /**
  14.   * @param ListNode $l1
  15.   * @param ListNode $l2
  16.   * @return ListNode
  17.   */
  18. function addTwoNumbers($l1, $l2) {
  19. $node=new ListNode($this->res + $l1->val + $l2->val);
  20. if($this->res=intval($node->val >9)){
  21. $node->val -=10;
  22. }
  23. $node->next=(!$this->res && is_null($l1->next) && is_null($l2->next) )?null:$this->addTwoNumbers($l1->next,$l2->next);
  24. return $node;
  25. }
  26. }