【问题标题】:How to multiply number until achieve single-digit numbers and counting the number?如何将数字相乘直到达到个位数并计数?
【发布时间】:2016-07-22 02:51:51
【问题描述】:

它的描述是这样的:

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

我只能这样:

$array = str_split(39);

    foreach ($array as $key => $value) {
        echo $array[$key]*$array[$key+1];
    }

接下来我很困惑

有什么办法可以解决我的问题吗?

【问题讨论】:

  • 我喜欢这个问题。除了在php 标签下询问的无聊、总是重复的东西之外,还有别的东西。 +1
  • @AlBundy 同意!有一个很好的机会来挖掘我的大脑:)
  • @DunnoHowToCode 你的回答对我来说太快了,但我们现在在欧洲 05:20 AM,我有 16 个小时的工作日,我的大脑现在正在关闭。 .

标签: php arrays foreach split


【解决方案1】:
$array = str_split('999'); //Your string
$j=0; //Counter for counting the number of iteration
while (count($array)>1){ //When more than 2 indexes in array
 for($i=0;$i<count($array);$i++){ //Iterate through all permutations
     $array = array_product($array); //Multiplies all numbers in array
     $array = str_split($array); //Split the array up again
     $j++; //Increment counter(as literal as I can sound)
 }
}
echo $j; //Print out the number of times

【讨论】:

【解决方案2】:

你也可以使用函数调用,直到它只有一个数字......

$count = 0;
persistence(2,$count);
function persistence($i,&$c){   
     $v = str_split($i);
        if(count($v) > 1){
            $total = array_product($v);
            $c++;
            persistence($total,$c);
        }
}
var_dump($count);

【讨论】:

    猜你喜欢
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 2012-11-07
    • 2011-03-04
    相关资源
    最近更新 更多