Passed
Push — master ( d0fbd1...0825db )
by Daniel
76:55 queued 39:08
created

altPersistence()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
4
5
For example:
6
7
persistence(39) === 3; // because 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4 and 4 has only one digit
8
persistence(999) === 4; // because 9 * 9 * 9 = 729, 7 * 2 * 9 = 126, 1 * 2 * 6 = 12, and finally 1 * 2 = 2
9
persistence(4) === 0; // because 4 is already a one-digit number
10
*/
11
12
/**
13
 * persistence
14
 *
15
 * @param  int $num
16
 * @return int
17
 */
18
function persistence(int $num): int
19
{
20
    // Ensure that $num is an integer
21
    $num = (int)$num;
22
    $total = 1;
23
    
24
    $numArray = str_split($num);
25
    $numArrayCount = count($numArray);
0 ignored issues
show
Bug introduced by
It seems like $numArray can also be of type true; however, parameter $value of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

25
    $numArrayCount = count(/** @scrutinizer ignore-type */ $numArray);
Loading history...
26
    $count = 0;
27
  
28
    if ($numArrayCount > 1) {
29
        for ($i = 0; $i < $numArrayCount; $i++) {
30
            $total *= $numArray[$i];      
31
        }
32
        $count++;
33
        if (strlen($total) > 1) {
34
            return $count + persistence($total);
35
        }  return $count;
36
    }  return $count;    
37
}
38
39
// Alternate solution - array_product multiplies all values in the array, so we wont need to use a loop
40
41
/**
42
 * altPersistence
43
 *
44
 * @param  mixed $num
45
 * @return int
46
 */
47
function altPersistence(int $num): int
48
{
49
    // Ensure that $num is an integer
50
    $num = (int)$num;
51
    $count = 0;
52
    while ($num > 9) {
53
        $num = array_product(str_split($num));
0 ignored issues
show
Bug introduced by
It seems like str_split($num) can also be of type true; however, parameter $array of array_product() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

53
        $num = array_product(/** @scrutinizer ignore-type */ str_split($num));
Loading history...
54
        $count++;
55
    }
56
  
57
    return $count;
58
}