在我的回文函数中,if-else-statement
返回undefined。基本上,我试图找到三位数的最大回文数。例如,有两位数:99 * 91 = 9009
。
var palindromic = function(n) {
var save,
result,
counter = 900;
var checker = function(string) {
s = string.toString();
if(!(s)) {
return true;
} else if(s[0] !== s[s.length - 1]) {
return false;
}
checker(s.slice(1, -1));
}
var recursive = function() {
result = counter * n;
if(counter === n) {
return;
} else if(checker(result)) { // this line of code here, undefined.
save = result;
}
counter++;
recursive();
}
recursive();
return save;
};
有什么问题?欢迎任何帮助!
答案 0 :(得分:1)
代码中有两个问题
checker()
应该有return checker(s.slice(1,-1));
作为最后一行。recursive()
checker(result)
为真时,递归()应该返回。这是更正后的代码。
var palindromic = function (n) {
var save,
result,
counter = 900;
var checker = function (s) {
//s = string.toString();
if ( !(s) ) {
return true;
} else if ( s[0] !== s[s.length-1] ) {
return false;
}
return checker(s.slice(1,-1));
}
var recursive = function () {
result = counter * n;
if ( counter === n ) {
return;
} else if ( checker(result + "") ) { // this line of code here, undefined.
save = result;
return;
}
counter++;
recursive();
}
recursive();
return save;
};
<强>输出:强>
palindromic(2)
2002
palindromic(3)
2772
palindromic(5)
5005
palindromic(6)
6006
palindromic(9)
8118
palindromic(23423)
188484881
答案 1 :(得分:0)
你可以在没有递归的情况下完成。
function strReverse(str) {
var reverse = "";
for(var i = (str.length - 1); i >= 0; i -= 1) {
reverse += str[i];
}
return reverse;
}
function palindromic(n) {
var highestPalindrom = 0;
// Start with the highest number!
for(var i = n; i > 1; i -= 1) {
// Start also with the highest number!
for(var j = n; j > 1; j -= 1) {
// Get product
var product = i * j;
// Compare the string in reverse with the string itself
// If it is true, then it is a palindrom!
if(strReverse(product.toString()) === product.toString()) {
highestPalindrom = product;
// Break inner loop
break;
}
}
// Break outer loop
break;
}
return highestPalindrom;
}
var hP = palindromic(99);
console.log(hP);
&#13;