标签归档:算法

计算一个数字能拆分计算的次数

编写一个函数persistence,它接受一个正参数num并返回其乘法持久性,即必须将num中的数字相乘到一个数字的次数。这是codewars上的一道习题,感觉挺有意思的。
示例:
persistence(39) === 3; // because 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4 and 4 has only one digit
persistence(999) === 4; // because 9 * 9 * 9 = 729, 7 * 2 * 9 = 126, 1 * 2 * 6 = 12, and finally 1 * 2 = 2
persistence(4) === 0; // because 4 is already a one-digit number

代码:

function persistence(int $num): int {
   if($num<10) return 0;
        $split_arr = str_split($num);
        $res = array_product($split_arr);
        return 1+persistence($res);

}
0