【问题标题】:Recursion counter doesn't work in codewars kata递归计数器在 codewars kata 中不起作用
【发布时间】:2021-07-14 09:30:34
【问题描述】:

目前正在尝试完成代码大战中的persistent bugger kata

我需要返回输入必须相乘的次数,直到它减少到一个数字(下面的完整任务说明)。

除了计数之外,一切似乎都可以正常工作。当我控制台日志时,它记录和运行的次数是正确的,但不是像 1,2,3 这样递增,而是像 2,2,4 这样的。

所以不是返回 3,而是返回 4。

我尽量不寻求有关 katas 的帮助,但这一次我完全不知道为什么计数首先跳过数字并且也没有增加。

任务:

编写一个函数,persistence,它接受一个正参数 num 并返回它的乘法持久性,这是您必须将 num 中的数字相乘直到达到单个数字的次数。

例如:

 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(num) {
  //console.log('here', num)
  if(num < 10) return 0;
  if(num === 25) return 2
  let spl = num.toString().split('');
  
  let result = 1;
  let count = 1;

  spl.forEach((s) => {
    let int = parseInt(s)
    result *= int;
    //count++;
  })
  
  //console.log(result)
  if(result > 9) {
    persistence(result)
    count++;
  }
  
 // console.log('count-->', count)
  return count;
}

一个子问题是输入 25 总是返回比它应该少的计数 1。我知道我的修复很差,再次感谢任何建议。

【问题讨论】:

  • 无论persistence()if (result &gt; 9) { ... } 中被调用多少次,您都只会增加一次count
  • 每次 if 语句为真时 count 不会增加吗?如果不是怎么来的?
  • 每次递归调用函数时都会有一个单独的count 变量。没有一个 count 可以用于所有调用。
  • persistence() 返回count。使用该返回值来计算实际结果。
  • 不明白你的意思,你能给我举个例子吗?

标签: javascript recursion


【解决方案1】:

剧透警告:这包含一个解决方案。如果你不想这样,请在结束前停下来。

您真的不想使用 count,因为正如人们指出的那样,它是一个局部变量。如果结果是单个数字,您也不会太努力地对结果进行特殊处理。让递归处理它。

因此:

  function persistence(num) {
  //console.log('here', num)
  if(num < 10) return 0;
  //still here, must be 2 or more digits
  let spl = num.toString().split('');
  
  let result = 1;

  spl.forEach((s) => {
    let int = parseInt(s)
    result *= int;
  })


 
  //console.log(result)
  
    return 1 + persistence(result)
  
}

【讨论】:

  • 非常感谢。我什至没有想过让递归处理我的条件。非常感谢您的帮助和知识。
【解决方案2】:

由于您已经在此处发布了完整的解决方案,其中包含对您的实施的修复,因此我将提供我认为更简单的版本。如果我们有一个函数来为我们创建数字产品,那么persistence 可以是这样简单的递归:

const persistence = (n) => 
  n < 10 ? 0 : 1 + persistence (digProduct (n))

您已经有了数字产品的代码,虽然它很好,但数学方法而不是基于字符串的方法更简洁一些。我们可以写它——也可以递归地写——就像

const digProduct = (n) => 
  n < 10 ? n : (n % 10) * digProduct (Math .floor (n / 10))

或者我们可以选择(n / 10) | 0 代替floor 调用。两者都是合理的。

综合起来,我们有:

const digProduct = (n) => 
  n < 10 ? n : (n % 10) * digProduct ((n / 10) | 0)

const persistence = (n) => 
  n < 10 ? 0 : 1 + persistence (digProduct (n))

const tests = [39, 999, 4, 25]
tests.forEach (n => console.log (`${n} --> ${persistence(n)}`))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2012-02-29
    • 1970-01-01
    相关资源
    最近更新 更多