假设我有两个字符串,n1 = abc和n2 = xyz。我如何打印" azbycx"递归?
这是我的代码。我正在练习字符串操作,我似乎无法找到解决方法。我已经用Google搜索了,似乎找不到一个。
document.write(practice("abc","xyz"));
function practice(n1,n2){
if(n1.length==0){return n2;}
if(n2.length==0){return n1;}
return n1.substring(0,1) + practice(n2.charAt(n2.length-1),n1.substring(1));
}
仅打印" azc" :(
答案 0 :(得分:2)
function practice(n1,n2){
console.log(n1);
console.log(n2);
if(n1.length==0){return n2;}
if(n2.length==0){return n1;}
return n1[0]+n2[n2.length-1] + practice(n1.substring(1), n2.substring(0, n2.length-1));
}
答案 1 :(得分:0)
function practice(n1,n2){
if(n1.length==0){return n2;}
if(n2.length==0){return n1;}
if (n2.length > n1.length) {
return n2.charAt(n2.length-1) + practice(n1, n2.substring(0, n2.length-1));
}
else {
return n1.charAt(0) + practice(n1.substring(1), n2);
}
}
答案 2 :(得分:0)
var practice = function(n1,n2) {
var _charA = n1.charAt(0)
var _charB = n2.charAt(n2.length-1)
var _res = "";
if(_charA != "" || _charB != "") {
_res = practice(n1.substring(1,[n1.length]),n2.substring(0,[n2.length-1]))
}
return _charA + _charB + _res;
}
practice("abcd", "uvwxyz")
//output - azbycxdwvu
答案 3 :(得分:0)
这可以做你喜欢的事情:
function practice(n1,n2){
if(n1.length==0 && n2.length==0)
return "";
return n1.substr(0,1) + n2.substr(n2.length-1, 1) +
practice(n1.substr(1, n1.length-1), n2.substr(0, n2.length-1));
}
jsfiddle here:http://jsfiddle.net/gt7fsb7g/