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

2020-09-04 16:44 By "Powerless" 2578 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 2020-02-07 18:57
  • 有状态服务VS无状态服务
    Posted on 2020-02-07 18:18
  • 企业级PAAS云平台几个关键问题和挑战
    Posted on 2019-06-12 18:33
  • MySQL 单库后期分库策略
    Posted on 2019-08-19 14:31
  • Redis七大经典问题
    Posted on 2021-05-27 11:14
  • 关于HTTPS的五大误区
    Posted on 2020-02-02 01:10
  • PHP实现精确发布时间
    Posted on 2018-12-06 21:00
  • 为什么要测量尾部延迟
    Posted on 2020-09-18 10:34

1.362177s