altPersistence()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 1
dl 0
loc 15
rs 9.9666
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
    // Additional type check
26
    if (true===$numArray) {
27
        return 0;
28
    }
29
    $numArrayCount = count($numArray);
30
    $count = 0;
31
  
32
    if ($numArrayCount > 1) {
33
        for ($i = 0; $i < $numArrayCount; $i++) {
34
            $total *= $numArray[$i];
35
        }
36
        $count++;
37
        if (strlen($total) > 1) {
38
            return $count + persistence($total);
39
        }
40
        return $count;
41
    }
42
    return $count;
43
}
44
45
// Alternate solution - array_product multiplies all values in the array, so we wont need to use a loop
46
47
/**
48
 * altPersistence
49
 *
50
 * @param  mixed $num
51
 * @return int
52
 */
53
function altPersistence(int $num): int
54
{
55
    // Ensure that $num is an integer
56
    $num = (int)$num;
57
    $splitNum = str_split($num);
58
    if (true===$splitNum) {
59
        return 0;
60
    }
61
    $count = 0;
62
    while ($num > 9) {
63
        $num = array_product($splitNum);
64
        $count++;
65
    }
66
  
67
    return $count;
68
}
69