Created
January 20, 2022 22:16
-
-
Save rfsbsb/dc6f8cc7a135bda650aaa902f949e355 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Node { | |
public $value; | |
public $next; | |
public function __construct($val) { | |
$this->value = $val; | |
} | |
} | |
class NodeSum { | |
public function sum($node1, $node2) { | |
$arr1 = []; | |
$arr2 = []; | |
while ($node1) { | |
$arr1[] = $node1->value; | |
$node1 = $node1->next; | |
} | |
while ($node2) { | |
$arr2[] = $node2->value; | |
$node2 = $node2->next; | |
} | |
$max_len = max(count($arr1), count($arr2)); | |
$arr3 = []; | |
$remainder = 0; | |
for ($i=0;$i<$max_len;$i++) { | |
$val1 = isset($arr1[$i]) ? $arr1[$i] : 0; | |
$val2 = isset($arr2[$i]) ? $arr2[$i] : 0; | |
$sum = $val1 + $val2 + $remainder; | |
$remainder = $sum < 10 ? 0 : 1; | |
$arr3[] = $sum >= 10 ? $sum - 10 : $sum; | |
if ($i === $max_len - 1 && $remainder > 0) { | |
$arr3[] = $remainder; | |
} | |
} | |
$newNode = new Node($arr3[0]); | |
$newMax = count($arr3); | |
for ($i=1;$i<$newMax;$i++) { | |
$newItem = new Node($arr3[$i]); | |
$newItem->next = $newNode; | |
$newNode = $newItem; | |
} | |
return $newNode; | |
} | |
} | |
$val1 = new Node(5); | |
$val1->next = new Node(6); | |
$val1->next->next = new Node(3); | |
$val2 = new Node(8); | |
$val2->next = new Node(4); | |
$val2->next->next = new Node(2); | |
$sum = new NodeSum(); | |
$sumNode = $sum->sum($val1, $val2); | |
while ($sumNode) { | |
print $sumNode->value; | |
$sumNode = $sumNode->next; | |
} | |
echo "\n"; | |
$val1 = new Node(7); | |
$val1->next = new Node(5); | |
$val1->next->next = new Node(9); | |
$val1->next->next->next = new Node(4); | |
$val1->next->next->next->next = new Node(6); | |
$val2 = new Node(8); | |
$val2->next = new Node(4); | |
$sum = new NodeSum(); | |
$sumNode = $sum->sum($val1, $val2); | |
while ($sumNode) { | |
print $sumNode->value; | |
$sumNode = $sumNode->next; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment