我有以下功能来解决Hackerrank Chocolate feast上的问题,但它似乎运行良好,但它会进行额外的循环,而不是终止最终给我未定义。什么是我错过任何帮助将不胜感激
function main() {
var t = parseInt(readLine());
for(var a0 = 0; a0 < t; a0++){
var n_temp = readLine().split(' ');
var n = parseInt(n_temp[0]);//amount
var c = parseInt(n_temp[1]);//cost
var m = parseInt(n_temp[2]);//number of wrappers recquired
var bought = Math.floor(n/c);
var count = 0;
var extra = swapWrap(bought);
var arr = new Array();
function swapWrap(x){
var freeChocolates = 0;
if(x >= m){
count += Math.floor(x/m);
freeChocolates = Math.floor(x/m);//chocolates I get after swapping
var remaining = x%m + freeChocolates;//remaining chocolate wrapper + free chocolate wrapper
swapWrap(remaining); //recurse
}else{
return count;
}
}
console.log(extra);
}
}
答案 0 :(得分:2)
如果您正在进行递归,则可能需要向此行添加一个返回
return swapWrap(remaining); //recurse