以递归方式使用适当的逗号打印数字

时间:2015-12-12 04:18:01

标签: java recursion

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);
             }
        }

3 个答案:

答案 0 :(得分:1)

您可以使用StringBuilder.reverse()在一行中反转String,例如

String str = "abc";
str = new StringBuilder(str).reverse().toString();

但您也可以使用printf 1 。像,

public static void print(int n) {
    System.out.printf("%,d%n", n);
}

public static void main(String[] args) {
    int num = 123456789;
    print(num);
}

输出(按要求)

123,456,789

1 有关更多选项,另请参阅The Java Tutorials - Formatting Numeric Print Output

答案 1 :(得分: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));
        }
}

说明:

  • 始终打印1 st 字符
  • 如果没有其他字符,请打印 CR
  • 如果要处理至少一个字符,请检查要处理的字符长度是否为3的倍数,如果是则打印“,”
  • 并使用字符串减去1 st 字符递归调用 print

答案 2 :(得分:0)

您可以使用以下DecimalFormat来完成工作。

String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");

System.out.println(formatter.format(amount));