地址:https://leetcode-cn.com/problems/add-two-numbers/

  1. <?php
  2. /**
  3. 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
  4. 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
  5. 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
  6. 示例:
  7. 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
  8. 输出:7 -> 0 -> 8
  9. 原因:342 + 465 = 807
  10. */
  11. /**
  12. * Definition for a singly-linked list.
  13. * class ListNode {
  14. * public $val = 0;
  15. * public $next = null;
  16. * function __construct($val) { $this->val = $val; }
  17. * }
  18. */
  19. class Solution {
  20. /**
  21. * 使用递归
  22. */
  23. function addTwoNumbers1($l1, $l2) {
  24. $this->add($l1,$l2,0);
  25. }
  26. /**
  27. * @param $l1
  28. * @param $l2
  29. * @param $jinwei
  30. * @return ListNode
  31. */
  32. function add($l1,$l2,$jinwei){
  33. //计算两数相加后的个位
  34. $sum = new ListNode(($l1->val + $l2->val + $jinwei) % 10);
  35. //计算两数相加后是否大于10,是则进1,否则进0
  36. $jinwei = floor(($l1->val + $l2->val + $jinwei) / 10);
  37. if ($l1->next || $l2->next || $jinwei) {
  38. //l1和l2的next都有可能是null,如果是null就给个0
  39. if (is_null($l1->next)) {
  40. $l1->next = new ListNode(0);
  41. }
  42. if (is_null($l2->next)) {
  43. $l2->next = new ListNode(0);
  44. }
  45. $sum->next = $this->add($l1->next, $l2->next, $jinwei);
  46. }
  47. return $sum;
  48. }
  49. /**
  50. 暴力解决
  51. */
  52. function addTwoNumbers2($l1, $l2) {
  53. $list = new ListNode(0);
  54. $cur = $list;
  55. $add = 0;
  56. while($l1 || $l2){
  57. $x = $l1 != null ?$l1->val :0;
  58. $y = $l2 != null ?$l2->val :0;
  59. $val = ($x+$y+$add)%10;
  60. $add = ($x+$y+$add)/10;
  61. $new = new ListNode($val);
  62. $cur->next = $new;
  63. $cur = $cur->next;
  64. if ($l1 != null){
  65. $l1 = $l1->next;
  66. }
  67. if ($l2 != null){
  68. $l2 = $l2->next;
  69. }
  70. }
  71. if ($add > 0 ){
  72. $cur->next = new ListNode($add);
  73. }
  74. return $list->next;
  75. }
  76. }

 

版权声明:本文为8013-cmf原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/8013-cmf/p/12655660.html