LeetCode 2. Add Two Numbers

May. 19, 2021

Here is my solution to Add Two Numbers problem in 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) {
        $ans = new ListNode(0, null);
        $p = $l1;
        $q = $l2;
        $current = $ans;
        $carry=0;

        while ($p != null || $q != null) {
            $x = isset($p) ? $p->val : 0;
            $y = isset($q) ? $q->val : 0;
            $sum = $carry + $x + $y;
            $carry = (int) ($sum/10);
            $current->next = new ListNode($sum%10);
            $current = $current->next;
            if ($p != null) $p = $p->next;
            if ($q != null) $q = $q->next;
        }
        if ($carry > 0) {
            $current->next = new ListNode($carry);
        }

        return $ans->next;
    }
}