Test Failed
Push — master ( 853c98...e3b2de )
by Jinyun
02:12
created

MultiplyStrings::multiply()   B

Complexity

Conditions 11
Paths 26

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 26
rs 7.3166
cc 11
nc 26
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class MultiplyStrings
8
{
9
    public static function multiply(string $p, string $q): string
10
    {
11
        if (empty($p) || empty($q)) {
12
            return '0';
13
        }
14
        if ($p === '0' && $q === '0') {
15
            return '0';
16
        }
17
18
        [$m, $n] = [strlen($p), strlen($q)];
19
        $map = array_fill(0, $m + $n, 0);
20
        for ($i = $m - 1; $i >= 0; $i--) {
21
            for ($j = $n - 1; $j >= 0; $j--) {
22
                [$k, $v] = [$i + $j + 1, $p[$i] * $q[$j]];
23
                $sum = $v + $map[$k];
24
                $map[$k] = $sum % 10;
25
                $map[$k - 1] += intdiv($sum, 10);
26
            }
27
        }
28
        $s = '';
29
        for ($i = 0; $i < ($m + $n) && $map[$i] === 0; $i++);
30
        for (; $i < ($m + $n); $i++) {
31
            $s .= $map[$i];
32
        }
33
34
        return strlen($s) === 0 ? '0' : $s;
35
    }
36
}
37