# Go 和 PHP 基于两组数计算相加的结果

hxd_ · · 307 次点击 · · 开始浏览

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

#### 解题思路

Go 实现

``````func addTwoNumbersOptimize(l1 *ListNode, l2 *ListNode) *ListNode {
var (
carry        int
currentValue int
centerValue  int
point        = &ListNode{}
)
for l1 != nil || l2 != nil || carry != 0 {
lValue := 0
rValue := 0
if l1 != nil {
lValue = l1.Val
l1 = l1.Next
}
if l2 != nil {
rValue = l2.Val
l2 = l2.Next
}
centerValue = lValue + rValue + carry
currentValue = centerValue % 10
carry = centerValue / 10
point.Next = &ListNode{Val: currentValue}
point = point.Next

}
}``````

PHP 实现

``````function addTwoNumbers(\$first, \$second)
{
\$carry = 0;
\$str = '';

// 循环次数以较长的数组为准
\$firstCount = count(\$first);
\$secondCount = count(\$second);
\$count = \$firstCount > \$secondCount ? \$firstCount : \$secondCount;

for (\$i = 0; \$i < \$count; \$i++) {
\$firstValue = \$first[0] ?? 0;
\$secondValue = \$second[0] ?? 0;
array_shift(\$first);
array_shift(\$second);

// 计算，额外处理最后一次的情况，在空字符串前追加数据
\$centerValue = \$firstValue + \$secondValue + \$carry;
\$currentValue = \$i === \$count - 1 ? (int)\$centerValue : \$centerValue % 10;
\$carry = \$centerValue / 10;
\$str = \$currentValue . \$str;
}

return \$str;
}

echo addTwoNumbers([2, 4, 3], [5, 6, 4]); // output: 807
echo addTwoNumbers([2, 4, 3], [5, 6, 7]); // output: 1107``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

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

#### 解题思路

Go 实现

``````func addTwoNumbersOptimize(l1 *ListNode, l2 *ListNode) *ListNode {
var (
carry        int
currentValue int
centerValue  int
point        = &ListNode{}
)
for l1 != nil || l2 != nil || carry != 0 {
lValue := 0
rValue := 0
if l1 != nil {
lValue = l1.Val
l1 = l1.Next
}
if l2 != nil {
rValue = l2.Val
l2 = l2.Next
}
centerValue = lValue + rValue + carry
currentValue = centerValue % 10
carry = centerValue / 10
point.Next = &ListNode{Val: currentValue}
point = point.Next

}
}``````

PHP 实现

``````function addTwoNumbers(\$first, \$second)
{
\$carry = 0;
\$str = '';

// 循环次数以较长的数组为准
\$firstCount = count(\$first);
\$secondCount = count(\$second);
\$count = \$firstCount > \$secondCount ? \$firstCount : \$secondCount;

for (\$i = 0; \$i < \$count; \$i++) {
\$firstValue = \$first[0] ?? 0;
\$secondValue = \$second[0] ?? 0;
array_shift(\$first);
array_shift(\$second);

// 计算，额外处理最后一次的情况，在空字符串前追加数据
\$centerValue = \$firstValue + \$secondValue + \$carry;
\$currentValue = \$i === \$count - 1 ? (int)\$centerValue : \$centerValue % 10;
\$carry = \$centerValue / 10;
\$str = \$currentValue . \$str;
}

return \$str;
}

echo addTwoNumbers([2, 4, 3], [5, 6, 4]); // output: 807
echo addTwoNumbers([2, 4, 3], [5, 6, 7]); // output: 1107``````