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

2020-09-04 16:44 By "Powerless" 2656 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

View in WeChat

Others Discussion

  • 初识七层、五层、四层网络协议
    Posted on 2021-04-09 16:52
  • Redis各种数据类型的使用场景举例分析【二】
    Posted on 2018-11-22 10:30
  • QPS、TPS、RT、吞吐量到底是什么
    Posted on 2020-02-02 01:15
  • 2018年云计算热词
    Posted on 2019-06-12 18:19
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • ACID原则
    Posted on 2020-12-17 16:36
  • 前端知识体系精简-Css
    Posted on 2018-03-28 18:34
  • 浏览器访问网站经历的步骤-Html
    Posted on 2018-11-28 18:48