PHP-字符串相乘

字符串相乘

题意

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式

示例1:

输入: num1 = "2", num2 = "3"
输出: "6"

示例2:

输入: num1 = "123", num2 = "456"
输出: "56088"

示例3:

输入: num1 = "999999999", num2 = "999999999"
输出: "999999998000000001"

解题思路:

模拟乘法公式进行计算

                 1     2     3
             *         2     2
        -------------------------
                 2     4     6
           2     4     6
        -------------------------
           2     7     0     6

代码

class Solution
{
    /**
     * @param String $num1
     * @param String $num2
     * @return String
     */
    public function multiply($num1, $num2)
    {
        if ($num1 == '0' || $num2 == '0') {
            return '0';
        }

        $strNum1 = $num1;
        $strNum2 = $num2;

        if (strlen($num1) < strlen($num2)) {
            $strNum1 = $num2;
            $strNum2 = $num1;
        }

        $size1  = strlen($strNum1) - 1;
        $size2  = strlen($strNum2) - 1;
        $sumArr = [];
        $k      = 0;

        //乘法公式计算
        for ($i = $size2; $i >= 0; $i--) {
            $q   = 0;
            $sum = ($k++ > 0) ? array_pad([], $k - 1, 0) : [];
            for ($j = $size1; $j >= 0; $j--) {
                $num   = $strNum2{$i} * $strNum1{$j} +$q;
                $c     = $num % 10;
                $q     = ($c != $num) ? floor($num / 10) : 0;
                $sum[] = $c;
            }
            if ($q != 0) {
                $sum[] = $q;
            }
            $sumArr[] = $sum;
        }

        //加法公式计算
        $i   = 0;
        $q   = 0;
        $end = count($sum);
        $sum = [];
        while (1) {
            $num = 0;
            foreach ($sumArr as $item) {
                $num += $item[$i];
            }
            $num = (($q != 0) ? $num + $q : $num);
            if ($i >= $end) {
                ($q != 0) ? $sum[] = $q : null;
                break;
            }
            $c     = $num % 10;
            $q     = ($c != $num) ? floor($num / 10) : 0;
            $sum[] = $c;
            $i++;
        }
        return join(array_reverse($sum), '');
    }
}

测试

print_r((new Solution())->multiply('123', '22')); //输出:2706
print_r((new Solution())->multiply('2', '3')); //输出:6
print_r((new Solution())->multiply('123', '456')); //输出:56088
print_r((new Solution())->multiply('999999999', '999999999')); //输出:999999998000000001

你可能感兴趣的:(PHP-字符串相乘)