【发布时间】:2021-10-03 10:18:51
【问题描述】:
//aim -> Given a number n, return the number of steps required to reach 1.
//ex -> when n=12, we get 9 steps
// export
const steps = (num) => {
//function to check if the number is positive integer
isValid=n=>n>0;
if(isValid(num)){
//base case -> the number becomes 1
if(num===1){
return 1;
}
//if the number is not equal to 1
else{
//if the number is even do n/2 and return it again
if(num%2===0){
return steps(num/2);
}
else{
return steps(3*num+1);
}
}
}
};
console.log( steps(12) )
/**
* lets do with recursion:
* take an input num
* if the number is 1, return 1 (base case)
* if the number is not 1 but even, do cal=num/2 and return step(cal) back to the function
* if the number is not 1 bu odd, do cal = 3*num+1
*/
当我控制台记录 isEven 时,我得到 1-> 3 次,当我执行 isOdd console.log 时,我得到了很多次。
这里有什么问题?以后我该如何预防?谢谢!
【问题讨论】:
-
这是一个让您熟悉调试器使用的好机会。使用浏览器的调试工具,您可以放置一个断点来暂停代码的执行,并逐行执行该执行,单步执行调用的函数等,观察变量值的变化。当你这样做时,哪个操作首先产生了意想不到的结果?使用了哪些值?结果如何?预期的结果是什么?为什么?
-
"当我控制台记录 isEven 时,我得到 1-> 3 次,当我执行 isOdd console.log 时,我得到了很多次。" @987654321 @。我看不出你认为问题出在哪里。
-
来自here 从n = 12开始,得到序列12、6、3、10、5、16、8、4、2、1 - 所以该序列中有三个奇数。也许您在 isOdd console.log 中看到了这一点,而代码中没有显示。
标签: javascript loops recursion