Java - number in expanded form

You could do the same with pure math, using modulo % and integer division /, e.g. using Stream API:

int n = 70304;
String res = IntStream
        .iterate(1, k -> n / k > 0, k -> k * 10) // divisors
        .map(k -> (n % (k*10) / k ) * k)         // get 1s, 10s, 100s, etc.
        .filter(x -> x > 0)                      // throw out zeros
        .mapToObj(Integer::toString)             // convert to string
        .collect(Collectors.joining(" + "));     // join with '+'
System.out.println(res); // 4 + 300 + 70000

Pseudocode uses integer arithmetics to extract decimal digits one-by-one (from the right one):

mul = 1    //will contain power of 10
while (num > 0):
     dig = num % 10    //integer modulo retrieves the last digit
     if (dig > 0):   //filter out zero summands
          add (dig * mul) to output   //like 3 * 100 = 300
     num = num / 10 //integer division removes the last decimal digit  6519 => 651
     mul = mul * 10    //updates power of 10 for the next digit

You should be adding '0's to str[i], not str[j]:

  for(int i = 0; i < str.length-1; i++) {
    if(Integer.valueOf(str[i]) > 0) {
      for(int j = i; j < str.length-1; j++) {
        str[i] += '0';
      }
    }
  }

This will result in:

70000 + 0 + 300 + 0 + 4

You still have to get rid of the 0 digits.

One possible way to get rid of them:

result = result.substring(1, result.length()-1).replace(", 0","").replace(",", " +");

Now the output is

70000 + 300 + 4

Tags:

Algorithm

Java