Home > OS >  Take in String that contains number characters and add commas to each thousands place WITHOUT conver
Take in String that contains number characters and add commas to each thousands place WITHOUT conver

Time:12-02

I want to take in a string for example "1234567890" and add commas to each thousands place in the number. However, I don't want to parse this string into an int or long. I think I might need to use recursion but I dont know how.

String number1 = "1234567890";
System.out.println(stringNumberAddCommas(number1));
//output == 1,234,567,890

public static String stringNumberAddCommas(String number1){  }

CodePudding user response:

There's no need to mess with recursion; all you need is to realize that you need to either work backwards or do some very basic math based on length.

Given a pile o digits that is, say, 8 characters long, that's all the information you need to know that the first comma is after 2 digits, and then every further comma at 3 digits from that position until you reach the end.

Tools needed:

  • "12345678".length() (= 8)
  • "12345678".substring(2, 5) (= "345")
  • a for (int i = ...; i < in.length(); i = 3) loop.
  • a new StringBuilder() along with its .append() method, both for appending the comma as well as those substrings.
  • Some exceedingly basic math on that length, involving in particular the % operator. a % b divides a by b, tosses the result in the garbage, and returns the leftovers. In other words, 5 % 3 returns 2 (because 5 divides into 3 one time, and that leaves a remainder of 2).

CodePudding user response:

    String test = "1234567890";
    String reversed = new StringBuffer(test).reverse().toString();
    int i = 0;
    StringBuilder ans = new StringBuilder();
    while(i 3<reversed.length()){
        ans.append(reversed, i, i   3).append(",");
        i =3;
    }
    ans.append(reversed, i, reversed.length());
    String solution = ans.reverse().toString();

CodePudding user response:

we can achieve this as below as well-

    public static String stringNumberAddCommas(String number) {
    for (int i = number.length() - 1; i >= 0; ) {
        if (i >= 3) {
            number = number.substring(0, i - 2)   ","   number.substring(i - 2);
        }
        i = i - 3;
    }
    System.out.println("number="   number);
    return number;
}
  • Related