示例输入 12345 应返回 12,345。我想我已经弄清楚了。唯一的问题是我得到的字符串是相反的(543,21)。现在我知道有一些方法可以很容易地反转字符串,但这会使运行时间变得更加复杂,所以我想知道是否有一种简单的方法可以在辅助本身内完成此操作?
public void print(int n){
String number = Integer.toString(n);
StringBuilder answer = new StringBuilder();
if(number.length() > 3){ //Only worry about adding commas if its more than three digits
printAux(number, answer, 1, number.length()-1);
System.out.println(answer);
}
}
private void printAux(String s, StringBuilder answer, int count, int index){
if(index < 0){
return;
}
else{
//If the counter is at the 4th index meaning it has passed three digits
if(count%3 == 1 && count > 3){
answer.append(",");
index = index + 1;
count = 0;
}
else{
answer.append(s.charAt(index));
}
printAux(s, answer, count + 1, index - 1);
}
}
最佳答案
简单一些
public static void print(String s) {
out.print(s.charAt(0));
if (s.length() == 1) out.print("\n");
else {
if (((s.length()-1) % 3) == 0) out.print(",");
print(s.substring(1));
}
}
说明:
- 始终打印第一个第个字符
- 如果没有更多字符,则打印CR
- 如果至少有一个字符要处理,检查要处理的长度是否是3的倍数,如果是则打印一个“,”
- 并用字符串减去第一个st字符递归调用print
关于java - 递归地打印带有适当逗号的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34236192/