【发布时间】:2020-05-01 08:32:05
【问题描述】:
任务是通过递归将字符串中的数字移动到字符串的开头。字符串中始终只包含一个数字。因此,如果我将“ba3nana”提供给代码,它应该返回“3banana”。已经做了一些递归任务,但我坚持这一点。我试过了,我猜已经有 50 种不同的组合,但到目前为止,我的代码只返回“banana3”,所以我的号码正好相反。我知道这段代码将每个数字都向右移动,但仍然无法找出正确的组合来获得左侧数字的输出。如果我改变一切,一切都会反过来变成“3ananab”
方法的调用如下所示:
System.out.println(shiftDigitLeft("ba3nana"));
这是目前返回banana3的代码:
private static String shiftDigitLeft(String text) {
if (text.isEmpty()) {
return text;
} else {
if (text.charAt(0) >= '\u0030' && text.charAt(0) <= '\u0039') {
return shiftDigitLeft(text.substring(1)) + text.charAt(0);
} else {
return text.charAt(0) + shiftDigitLeft(text.substring(1));
}
}
}
如果有人能告诉我它是如何正确完成的,将不胜感激,在此先感谢!
【问题讨论】: