php实现两个大数相加

PHP语言实现两个大数相加

/**
     * add
     * a,b should be numeric
     * @param $a string
     * @param $b string
     * @return string
     */
    function add($a, $b)
    {
        $lenA = strlen($a);
        $lenB = strlen($b);

        $j = 0; //进位数
        $re = '';
        for ($inxA = $lenA - 1, $inxB = $lenB - 1; ($inxA >= 0 || $inxB >= 0); --$inxA, --$inxB) {
            $itemA = ($inxA >= 0) ? (int)$a[$inxA] : 0;
            $itemB = ($inxB >= 0) ? (int)$b[$inxB] : 0;
            $sum = $itemA + $itemB + $j;
            if ($sum > 9) {
                $j = 1;
                $sum = $sum - 10;
            } else {
                $j = 0;
            }
            $re = (string)$sum . $re;
        }
        if ($j > 0) {
            $re = (string)$j . $re;
        }

        return $re;
    }
在使用的时候,直接调用该方法即可。

猜你喜欢

转载自blog.csdn.net/chinawangfei/article/details/79456255