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

2020-09-04 16:44 By "Powerless" 2717 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 2018-11-28 19:10
  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • QPS、TPS、RT、吞吐量到底是什么
    Posted on 2020-02-02 01:15
  • MySQL事务介绍
    Posted on 2019-06-05 18:14
  • 能创建多少个 TCP 连接?
    Posted on 2021-08-02 16:00
  • MySQL中的行级锁,表级锁,页级锁
    Posted on 2018-08-25 11:00
  • 2018年云计算热词
    Posted on 2019-06-12 18:19
  • PHP 基金会来啦!
    Posted on 2022-10-08 17:40