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

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

  • 2018年云计算热词
    Posted on 2019-06-12 18:19
  • PHP 基金会来啦!
    Posted on 2022-10-08 17:40
  • 快速了解Kafka
    Posted on 2021-03-25 14:20
  • Redis各种数据类型的使用场景举例分析【二】
    Posted on 2018-11-22 10:30
  • TCP协议的特性
    Posted on 2019-04-26 16:46
  • 让你的PHP7更快(GCC PGO)
    Posted on 2018-03-07 14:09
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • BASE原则
    Posted on 2020-12-17 16:42