PHP练习-计算两个超大整数相加的结果

2020-09-04 16:44 By "Powerless" 2705 2 1

思路分析

将超大整数逐个拆分位单个字符,按位相加。

function sumStr($str1,$str2)
{
    $c1 = strlen($str1)-1;
    $c2 = strlen($str2)-1;
    $i = $c1 > $c2 ? $c1 : $c2;
    $str = '';
    $surplus = 0;
    for (; $i>=0; $i--,$c1--,$c2--){
        $sum = 0;
        if($c1 >= 0 && $c2 >= 0){
            $sum = $str1[$c1] + $str2[$c2] + $surplus;
        }elseif($c1 < 0){
            $sum = $str2[$c2] + $surplus;
        }elseif($c2 < 0){
            $sum = $str1[$c1] + $surplus;
        }
        if($sum > 9){
            $str[$i] = $sum - 10;
            $surplus = 1;
        }else{
            $str[$i] = $sum;
            $surplus = 0;
        }
        if(!$i && $surplus){
            $str = $surplus.$str;
        }
    }
    return $str;
}
$s1 = '897685675463468768967';
$s2 = '42423476898765356';
echo sumStr($s1,$s2);

输出结果:897728098940367534323

评 论

唐朝 1 2020-09-10 11:01
11111
唐朝 1 2020-09-10 11:01
11111

Others Discussion

  • 初识七层、五层、四层网络协议
    Posted on 2021-04-09 16:52
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • PHP扩展安装
    Posted on 2019-06-24 11:28
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • ACID原则
    Posted on 2020-12-17 16:36
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • MySQL分组
    Posted on 2019-11-18 14:00