leetcode经典题目-两数相加(PHP解法)

LeetCode题目

给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

难度

中等

解法

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {
    function addTwoNumbers($l1, $l2) {
        $headNode = $currentNode = new ListNode(0);
        $addCount = 0;
        while ($l1 != null) {
            if ($l2 != null) {
                $l2Val = $l2->val;
            } else {
                $l2Val = 0;
            }
            $nextNode = new ListNode(0);
            $currentNode->next = $nextNode;
            $l1Val = $l1->val;
            $l3Val = $l2Val + $l1Val + $addCount;
            $addCount = 0;
            if ($l3Val >= 10) {
                $addCount++;
                $l3Val -= 10;
            }
            $nextNode->val = $l3Val;
            $l1 = $l1->next;
            if ($l2 != null) {
                $l2 = $l2->next;
            } else
                $l2 = null;
            $currentNode = $nextNode;
        }
        while ($l2 != null) {
            $nextNode = new ListNode(0);
            $currentNode->next = $nextNode;
            $val = $l2->val + $addCount;
            $addCount = 0;
            if ($val >= 10) {
                $addCount++;
                $val -= 10;
            }
            $nextNode->val = $val;
            $l2 = $l2->next;
            $currentNode = $nextNode;
        }
        if ($addCount != 0) {
            $nextNode = new ListNode(0);
            $currentNode->next = $nextNode;
            $nextNode->val = $addCount;
        }
        return $headNode->next;
    }
}

执行结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值