Java - number in expanded form

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
11
down vote

favorite












I have given number and want it to return as a String in expanded form. For example



expandedForm(12); # Should return "10 + 2"
expandedForm(42); # Should return "40 + 2"
expandedForm(70304); # Should return "70000 + 300 + 4"


My function works for first and second case, but with 70304 it gives this:



70 + 00 + 300 + 000 + 4


Here's my code



import java.util.Arrays;


public static String expandedForm(int num)


String str = Integer.toString(num).split("");
String result = "";

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[j] += '0';




result = Arrays.toString(str);
result = result.substring(1, result.length()-1).replace(",", " +");
System.out.println(result);

return result;



I think there's a problem with the second loop, but can't figure out why.







share|improve this question
























    up vote
    11
    down vote

    favorite












    I have given number and want it to return as a String in expanded form. For example



    expandedForm(12); # Should return "10 + 2"
    expandedForm(42); # Should return "40 + 2"
    expandedForm(70304); # Should return "70000 + 300 + 4"


    My function works for first and second case, but with 70304 it gives this:



    70 + 00 + 300 + 000 + 4


    Here's my code



    import java.util.Arrays;


    public static String expandedForm(int num)


    String str = Integer.toString(num).split("");
    String result = "";

    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[j] += '0';




    result = Arrays.toString(str);
    result = result.substring(1, result.length()-1).replace(",", " +");
    System.out.println(result);

    return result;



    I think there's a problem with the second loop, but can't figure out why.







    share|improve this question






















      up vote
      11
      down vote

      favorite









      up vote
      11
      down vote

      favorite











      I have given number and want it to return as a String in expanded form. For example



      expandedForm(12); # Should return "10 + 2"
      expandedForm(42); # Should return "40 + 2"
      expandedForm(70304); # Should return "70000 + 300 + 4"


      My function works for first and second case, but with 70304 it gives this:



      70 + 00 + 300 + 000 + 4


      Here's my code



      import java.util.Arrays;


      public static String expandedForm(int num)


      String str = Integer.toString(num).split("");
      String result = "";

      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[j] += '0';




      result = Arrays.toString(str);
      result = result.substring(1, result.length()-1).replace(",", " +");
      System.out.println(result);

      return result;



      I think there's a problem with the second loop, but can't figure out why.







      share|improve this question












      I have given number and want it to return as a String in expanded form. For example



      expandedForm(12); # Should return "10 + 2"
      expandedForm(42); # Should return "40 + 2"
      expandedForm(70304); # Should return "70000 + 300 + 4"


      My function works for first and second case, but with 70304 it gives this:



      70 + 00 + 300 + 000 + 4


      Here's my code



      import java.util.Arrays;


      public static String expandedForm(int num)


      String str = Integer.toString(num).split("");
      String result = "";

      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[j] += '0';




      result = Arrays.toString(str);
      result = result.substring(1, result.length()-1).replace(",", " +");
      System.out.println(result);

      return result;



      I think there's a problem with the second loop, but can't figure out why.









      share|improve this question











      share|improve this question




      share|improve this question










      asked Sep 6 at 11:22









      Asia

      786




      786






















          7 Answers
          7






          active

          oldest

          votes

















          up vote
          13
          down vote



          accepted










          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





          share|improve this answer




















          • result.replace(" + 0","") would be easier?
            – Viktor Mellgren
            Sep 6 at 12:10


















          up vote
          6
          down vote













          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





          share|improve this answer





























            up vote
            3
            down vote













            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





            share|improve this answer
















            • 1




              Why the downvote? If because the terms are in reverse order, well, if that is important, the order could easily be fixed.
              – tobias_k
              Sep 6 at 16:12

















            up vote
            2
            down vote













            There are many variations possible. If the usage of a list is allowed:



            public static String expandedForm(int num)

            String str = Integer.toString(num).split("");
            String result;
            List<String> l = new ArrayList<String>();

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

            l.add(s);



            result = l.toString();
            result = result.substring(1, result.length() - 1).replace(",", " +");
            System.out.println(result);

            return result;



            One could also work directly on result:



            public static String expandedForm2(int num)

            String str = Integer.toString(num).split("");
            String result = "";

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

            result += " + ";


            result = result.substring(0, result.length() - 3);
            System.out.println(result);
            return result;






            share|improve this answer





























              up vote
              0
              down vote













              package backup;

              import java.util.Arrays;

              public class FileOutput

              public static void main(String args)

              String expForm = expandedForm(70304);
              //System.out.println(expForm);



              public static String expandedForm(int num)


              String str = Integer.toString(num).split("");
              String result = "";

              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';




              result = Arrays.toString(str);
              result = result.substring(1, result.length()-1).replace(",", " +");
              System.out.println(result);

              return result;




              Output : 70000 + 0 + 300 + 0 + 4



              Solution in most inner loop you need to add '0' to str[i] : str[i] += '0';



              Then you need to replace "+ 0" from the resulted output.






              share|improve this answer



























                up vote
                0
                down vote













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








                share|improve this answer
















                • 4




                  You should add explanations to your answers, not only paste code.
                  – Nidhoegger
                  Sep 6 at 17:18

















                up vote
                0
                down vote













                This is also possible to do recursively. Here an example implementation:



                String g(int n, int depth) // Recursive method with 2 int parameters & String return-type
                int remainder = n % depth; // The current recursive remainder
                if(depth < n) // If we aren't done with the number yet:
                int nextDepth = depth * 10; // Go to the next depth (of the power of 10)
                int nextN = n - remainder; // Remove the remainder from the input `n`
                // Do a recursive call with these next `n` and `depth`
                String resultRecursiveCall = g(nextN, nextDepth);
                if(remainder != 0) // If the remainder was not 0:
                // Append a " + " and this remainder to the result
                resultRecursiveCall += " + " + remainder;

                return resultRecursiveCall; // And return the result
                else // Else:
                return Integer.toString(n); // Simply return input `n` as result



                String f(int n) // Second method so we can accept just integer `n`
                return g(n, 1); // Which will call the recursive call with parameters `n` and 1



                The second method is so we can call the method with just a single input n. For example:



                String result = f(70304);


                Which will result in the String 70000 + 300 + 4.



                Try it online.




                To explain a bit more in depth of what this recursive method does, let's just do a step-by-step for the input 70304:



                1. In the first recursive iteration: n=70304, depth=1, remainder=70304%1 = 0.

                  • Since depth < n is truthy, it will do a recursive call with 70304-0 and 1*10

                  • And since remainder is 0, it will append nothing more to the result


                2. In the second recursive iteration: n=70304, depth=10, remainder=70304%10 = 4.

                  • Since depth < n is still truthy, it will do a recursive call with 70304-4 and 10*10

                  • And since remainder is 4, it will append a " + " and this 4 to the result


                3. In the third recursive iteration: n=70300, depth=100, remainder=70300%100 = 0.

                  • Since depth < n is still truthy, it will do a recursive call with 70300-0 and 100*10

                  • And since remainder is 0, it will append nothing more to the result


                4. In the fourth recursive iteration: n=70300, depth=1000, remainder=70300%1000 = 300.

                  • Since depth < n is still truthy, it will do a recursive call with 70300-300 and 1000*10

                  • And since remainder is 300, it will append a " + " and this 300 to the result


                5. In the fifth recursive iteration: n=70000, depth=10000, remainder=70000%10000 = 0.

                  • Since depth < n is still truthy, it will do a recursive call with 70000-0 and 10000*10

                  • And since remainder is 0, it will append nothing more to the result


                6. In the sixth recursive iteration: n=70000, depth=100000, remainder=70000%100000 = 70000.

                  • Since now depth < n is falsey, it won't do any more recursive calls, but instead return the current n (which is 70000).


                And since these were all recursive calls, we should actually look at it backwards for the result, so it will result in 70000 + 300 + 4.



                So in general:



                • The depth < n if-check is to see when we are done with the recursive calls.

                • The g(n-remainder, depth*10) will remove the digits we've already output in a previous recursive iteration, and goes to the next 10k power in the next recursive iteration

                • The remainder != 0 if-check determines if the number we want to append was not a 0





                share|improve this answer




















                  Your Answer





                  StackExchange.ifUsing("editor", function ()
                  StackExchange.using("externalEditor", function ()
                  StackExchange.using("snippets", function ()
                  StackExchange.snippets.init();
                  );
                  );
                  , "code-snippets");

                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "1"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  convertImagesToLinks: true,
                  noModals: false,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                   

                  draft saved


                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52202986%2fjava-number-in-expanded-form%23new-answer', 'question_page');

                  );

                  Post as a guest






























                  7 Answers
                  7






                  active

                  oldest

                  votes








                  7 Answers
                  7






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes








                  up vote
                  13
                  down vote



                  accepted










                  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





                  share|improve this answer




















                  • result.replace(" + 0","") would be easier?
                    – Viktor Mellgren
                    Sep 6 at 12:10















                  up vote
                  13
                  down vote



                  accepted










                  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





                  share|improve this answer




















                  • result.replace(" + 0","") would be easier?
                    – Viktor Mellgren
                    Sep 6 at 12:10













                  up vote
                  13
                  down vote



                  accepted







                  up vote
                  13
                  down vote



                  accepted






                  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





                  share|improve this answer












                  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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 6 at 11:31









                  Eran

                  262k33406491




                  262k33406491











                  • result.replace(" + 0","") would be easier?
                    – Viktor Mellgren
                    Sep 6 at 12:10

















                  • result.replace(" + 0","") would be easier?
                    – Viktor Mellgren
                    Sep 6 at 12:10
















                  result.replace(" + 0","") would be easier?
                  – Viktor Mellgren
                  Sep 6 at 12:10





                  result.replace(" + 0","") would be easier?
                  – Viktor Mellgren
                  Sep 6 at 12:10













                  up vote
                  6
                  down vote













                  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





                  share|improve this answer


























                    up vote
                    6
                    down vote













                    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





                    share|improve this answer
























                      up vote
                      6
                      down vote










                      up vote
                      6
                      down vote









                      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





                      share|improve this answer














                      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






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Sep 6 at 13:03

























                      answered Sep 6 at 11:32









                      MBo

                      42.4k22847




                      42.4k22847




















                          up vote
                          3
                          down vote













                          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





                          share|improve this answer
















                          • 1




                            Why the downvote? If because the terms are in reverse order, well, if that is important, the order could easily be fixed.
                            – tobias_k
                            Sep 6 at 16:12














                          up vote
                          3
                          down vote













                          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





                          share|improve this answer
















                          • 1




                            Why the downvote? If because the terms are in reverse order, well, if that is important, the order could easily be fixed.
                            – tobias_k
                            Sep 6 at 16:12












                          up vote
                          3
                          down vote










                          up vote
                          3
                          down vote









                          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





                          share|improve this answer












                          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






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Sep 6 at 15:43









                          tobias_k

                          54.4k963100




                          54.4k963100







                          • 1




                            Why the downvote? If because the terms are in reverse order, well, if that is important, the order could easily be fixed.
                            – tobias_k
                            Sep 6 at 16:12












                          • 1




                            Why the downvote? If because the terms are in reverse order, well, if that is important, the order could easily be fixed.
                            – tobias_k
                            Sep 6 at 16:12







                          1




                          1




                          Why the downvote? If because the terms are in reverse order, well, if that is important, the order could easily be fixed.
                          – tobias_k
                          Sep 6 at 16:12




                          Why the downvote? If because the terms are in reverse order, well, if that is important, the order could easily be fixed.
                          – tobias_k
                          Sep 6 at 16:12










                          up vote
                          2
                          down vote













                          There are many variations possible. If the usage of a list is allowed:



                          public static String expandedForm(int num)

                          String str = Integer.toString(num).split("");
                          String result;
                          List<String> l = new ArrayList<String>();

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

                          l.add(s);



                          result = l.toString();
                          result = result.substring(1, result.length() - 1).replace(",", " +");
                          System.out.println(result);

                          return result;



                          One could also work directly on result:



                          public static String expandedForm2(int num)

                          String str = Integer.toString(num).split("");
                          String result = "";

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

                          result += " + ";


                          result = result.substring(0, result.length() - 3);
                          System.out.println(result);
                          return result;






                          share|improve this answer


























                            up vote
                            2
                            down vote













                            There are many variations possible. If the usage of a list is allowed:



                            public static String expandedForm(int num)

                            String str = Integer.toString(num).split("");
                            String result;
                            List<String> l = new ArrayList<String>();

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

                            l.add(s);



                            result = l.toString();
                            result = result.substring(1, result.length() - 1).replace(",", " +");
                            System.out.println(result);

                            return result;



                            One could also work directly on result:



                            public static String expandedForm2(int num)

                            String str = Integer.toString(num).split("");
                            String result = "";

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

                            result += " + ";


                            result = result.substring(0, result.length() - 3);
                            System.out.println(result);
                            return result;






                            share|improve this answer
























                              up vote
                              2
                              down vote










                              up vote
                              2
                              down vote









                              There are many variations possible. If the usage of a list is allowed:



                              public static String expandedForm(int num)

                              String str = Integer.toString(num).split("");
                              String result;
                              List<String> l = new ArrayList<String>();

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

                              l.add(s);



                              result = l.toString();
                              result = result.substring(1, result.length() - 1).replace(",", " +");
                              System.out.println(result);

                              return result;



                              One could also work directly on result:



                              public static String expandedForm2(int num)

                              String str = Integer.toString(num).split("");
                              String result = "";

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

                              result += " + ";


                              result = result.substring(0, result.length() - 3);
                              System.out.println(result);
                              return result;






                              share|improve this answer














                              There are many variations possible. If the usage of a list is allowed:



                              public static String expandedForm(int num)

                              String str = Integer.toString(num).split("");
                              String result;
                              List<String> l = new ArrayList<String>();

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

                              l.add(s);



                              result = l.toString();
                              result = result.substring(1, result.length() - 1).replace(",", " +");
                              System.out.println(result);

                              return result;



                              One could also work directly on result:



                              public static String expandedForm2(int num)

                              String str = Integer.toString(num).split("");
                              String result = "";

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

                              result += " + ";


                              result = result.substring(0, result.length() - 3);
                              System.out.println(result);
                              return result;







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Sep 6 at 18:25

























                              answered Sep 6 at 18:18









                              Imago

                              257312




                              257312




















                                  up vote
                                  0
                                  down vote













                                  package backup;

                                  import java.util.Arrays;

                                  public class FileOutput

                                  public static void main(String args)

                                  String expForm = expandedForm(70304);
                                  //System.out.println(expForm);



                                  public static String expandedForm(int num)


                                  String str = Integer.toString(num).split("");
                                  String result = "";

                                  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';




                                  result = Arrays.toString(str);
                                  result = result.substring(1, result.length()-1).replace(",", " +");
                                  System.out.println(result);

                                  return result;




                                  Output : 70000 + 0 + 300 + 0 + 4



                                  Solution in most inner loop you need to add '0' to str[i] : str[i] += '0';



                                  Then you need to replace "+ 0" from the resulted output.






                                  share|improve this answer
























                                    up vote
                                    0
                                    down vote













                                    package backup;

                                    import java.util.Arrays;

                                    public class FileOutput

                                    public static void main(String args)

                                    String expForm = expandedForm(70304);
                                    //System.out.println(expForm);



                                    public static String expandedForm(int num)


                                    String str = Integer.toString(num).split("");
                                    String result = "";

                                    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';




                                    result = Arrays.toString(str);
                                    result = result.substring(1, result.length()-1).replace(",", " +");
                                    System.out.println(result);

                                    return result;




                                    Output : 70000 + 0 + 300 + 0 + 4



                                    Solution in most inner loop you need to add '0' to str[i] : str[i] += '0';



                                    Then you need to replace "+ 0" from the resulted output.






                                    share|improve this answer






















                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      package backup;

                                      import java.util.Arrays;

                                      public class FileOutput

                                      public static void main(String args)

                                      String expForm = expandedForm(70304);
                                      //System.out.println(expForm);



                                      public static String expandedForm(int num)


                                      String str = Integer.toString(num).split("");
                                      String result = "";

                                      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';




                                      result = Arrays.toString(str);
                                      result = result.substring(1, result.length()-1).replace(",", " +");
                                      System.out.println(result);

                                      return result;




                                      Output : 70000 + 0 + 300 + 0 + 4



                                      Solution in most inner loop you need to add '0' to str[i] : str[i] += '0';



                                      Then you need to replace "+ 0" from the resulted output.






                                      share|improve this answer












                                      package backup;

                                      import java.util.Arrays;

                                      public class FileOutput

                                      public static void main(String args)

                                      String expForm = expandedForm(70304);
                                      //System.out.println(expForm);



                                      public static String expandedForm(int num)


                                      String str = Integer.toString(num).split("");
                                      String result = "";

                                      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';




                                      result = Arrays.toString(str);
                                      result = result.substring(1, result.length()-1).replace(",", " +");
                                      System.out.println(result);

                                      return result;




                                      Output : 70000 + 0 + 300 + 0 + 4



                                      Solution in most inner loop you need to add '0' to str[i] : str[i] += '0';



                                      Then you need to replace "+ 0" from the resulted output.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Sep 6 at 11:33









                                      Raj

                                      28912




                                      28912




















                                          up vote
                                          0
                                          down vote













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








                                          share|improve this answer
















                                          • 4




                                            You should add explanations to your answers, not only paste code.
                                            – Nidhoegger
                                            Sep 6 at 17:18














                                          up vote
                                          0
                                          down vote













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








                                          share|improve this answer
















                                          • 4




                                            You should add explanations to your answers, not only paste code.
                                            – Nidhoegger
                                            Sep 6 at 17:18












                                          up vote
                                          0
                                          down vote










                                          up vote
                                          0
                                          down vote









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








                                          share|improve this answer












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









                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Sep 6 at 11:35









                                          Bartek Wichowski

                                          434416




                                          434416







                                          • 4




                                            You should add explanations to your answers, not only paste code.
                                            – Nidhoegger
                                            Sep 6 at 17:18












                                          • 4




                                            You should add explanations to your answers, not only paste code.
                                            – Nidhoegger
                                            Sep 6 at 17:18







                                          4




                                          4




                                          You should add explanations to your answers, not only paste code.
                                          – Nidhoegger
                                          Sep 6 at 17:18




                                          You should add explanations to your answers, not only paste code.
                                          – Nidhoegger
                                          Sep 6 at 17:18










                                          up vote
                                          0
                                          down vote













                                          This is also possible to do recursively. Here an example implementation:



                                          String g(int n, int depth) // Recursive method with 2 int parameters & String return-type
                                          int remainder = n % depth; // The current recursive remainder
                                          if(depth < n) // If we aren't done with the number yet:
                                          int nextDepth = depth * 10; // Go to the next depth (of the power of 10)
                                          int nextN = n - remainder; // Remove the remainder from the input `n`
                                          // Do a recursive call with these next `n` and `depth`
                                          String resultRecursiveCall = g(nextN, nextDepth);
                                          if(remainder != 0) // If the remainder was not 0:
                                          // Append a " + " and this remainder to the result
                                          resultRecursiveCall += " + " + remainder;

                                          return resultRecursiveCall; // And return the result
                                          else // Else:
                                          return Integer.toString(n); // Simply return input `n` as result



                                          String f(int n) // Second method so we can accept just integer `n`
                                          return g(n, 1); // Which will call the recursive call with parameters `n` and 1



                                          The second method is so we can call the method with just a single input n. For example:



                                          String result = f(70304);


                                          Which will result in the String 70000 + 300 + 4.



                                          Try it online.




                                          To explain a bit more in depth of what this recursive method does, let's just do a step-by-step for the input 70304:



                                          1. In the first recursive iteration: n=70304, depth=1, remainder=70304%1 = 0.

                                            • Since depth < n is truthy, it will do a recursive call with 70304-0 and 1*10

                                            • And since remainder is 0, it will append nothing more to the result


                                          2. In the second recursive iteration: n=70304, depth=10, remainder=70304%10 = 4.

                                            • Since depth < n is still truthy, it will do a recursive call with 70304-4 and 10*10

                                            • And since remainder is 4, it will append a " + " and this 4 to the result


                                          3. In the third recursive iteration: n=70300, depth=100, remainder=70300%100 = 0.

                                            • Since depth < n is still truthy, it will do a recursive call with 70300-0 and 100*10

                                            • And since remainder is 0, it will append nothing more to the result


                                          4. In the fourth recursive iteration: n=70300, depth=1000, remainder=70300%1000 = 300.

                                            • Since depth < n is still truthy, it will do a recursive call with 70300-300 and 1000*10

                                            • And since remainder is 300, it will append a " + " and this 300 to the result


                                          5. In the fifth recursive iteration: n=70000, depth=10000, remainder=70000%10000 = 0.

                                            • Since depth < n is still truthy, it will do a recursive call with 70000-0 and 10000*10

                                            • And since remainder is 0, it will append nothing more to the result


                                          6. In the sixth recursive iteration: n=70000, depth=100000, remainder=70000%100000 = 70000.

                                            • Since now depth < n is falsey, it won't do any more recursive calls, but instead return the current n (which is 70000).


                                          And since these were all recursive calls, we should actually look at it backwards for the result, so it will result in 70000 + 300 + 4.



                                          So in general:



                                          • The depth < n if-check is to see when we are done with the recursive calls.

                                          • The g(n-remainder, depth*10) will remove the digits we've already output in a previous recursive iteration, and goes to the next 10k power in the next recursive iteration

                                          • The remainder != 0 if-check determines if the number we want to append was not a 0





                                          share|improve this answer
























                                            up vote
                                            0
                                            down vote













                                            This is also possible to do recursively. Here an example implementation:



                                            String g(int n, int depth) // Recursive method with 2 int parameters & String return-type
                                            int remainder = n % depth; // The current recursive remainder
                                            if(depth < n) // If we aren't done with the number yet:
                                            int nextDepth = depth * 10; // Go to the next depth (of the power of 10)
                                            int nextN = n - remainder; // Remove the remainder from the input `n`
                                            // Do a recursive call with these next `n` and `depth`
                                            String resultRecursiveCall = g(nextN, nextDepth);
                                            if(remainder != 0) // If the remainder was not 0:
                                            // Append a " + " and this remainder to the result
                                            resultRecursiveCall += " + " + remainder;

                                            return resultRecursiveCall; // And return the result
                                            else // Else:
                                            return Integer.toString(n); // Simply return input `n` as result



                                            String f(int n) // Second method so we can accept just integer `n`
                                            return g(n, 1); // Which will call the recursive call with parameters `n` and 1



                                            The second method is so we can call the method with just a single input n. For example:



                                            String result = f(70304);


                                            Which will result in the String 70000 + 300 + 4.



                                            Try it online.




                                            To explain a bit more in depth of what this recursive method does, let's just do a step-by-step for the input 70304:



                                            1. In the first recursive iteration: n=70304, depth=1, remainder=70304%1 = 0.

                                              • Since depth < n is truthy, it will do a recursive call with 70304-0 and 1*10

                                              • And since remainder is 0, it will append nothing more to the result


                                            2. In the second recursive iteration: n=70304, depth=10, remainder=70304%10 = 4.

                                              • Since depth < n is still truthy, it will do a recursive call with 70304-4 and 10*10

                                              • And since remainder is 4, it will append a " + " and this 4 to the result


                                            3. In the third recursive iteration: n=70300, depth=100, remainder=70300%100 = 0.

                                              • Since depth < n is still truthy, it will do a recursive call with 70300-0 and 100*10

                                              • And since remainder is 0, it will append nothing more to the result


                                            4. In the fourth recursive iteration: n=70300, depth=1000, remainder=70300%1000 = 300.

                                              • Since depth < n is still truthy, it will do a recursive call with 70300-300 and 1000*10

                                              • And since remainder is 300, it will append a " + " and this 300 to the result


                                            5. In the fifth recursive iteration: n=70000, depth=10000, remainder=70000%10000 = 0.

                                              • Since depth < n is still truthy, it will do a recursive call with 70000-0 and 10000*10

                                              • And since remainder is 0, it will append nothing more to the result


                                            6. In the sixth recursive iteration: n=70000, depth=100000, remainder=70000%100000 = 70000.

                                              • Since now depth < n is falsey, it won't do any more recursive calls, but instead return the current n (which is 70000).


                                            And since these were all recursive calls, we should actually look at it backwards for the result, so it will result in 70000 + 300 + 4.



                                            So in general:



                                            • The depth < n if-check is to see when we are done with the recursive calls.

                                            • The g(n-remainder, depth*10) will remove the digits we've already output in a previous recursive iteration, and goes to the next 10k power in the next recursive iteration

                                            • The remainder != 0 if-check determines if the number we want to append was not a 0





                                            share|improve this answer






















                                              up vote
                                              0
                                              down vote










                                              up vote
                                              0
                                              down vote









                                              This is also possible to do recursively. Here an example implementation:



                                              String g(int n, int depth) // Recursive method with 2 int parameters & String return-type
                                              int remainder = n % depth; // The current recursive remainder
                                              if(depth < n) // If we aren't done with the number yet:
                                              int nextDepth = depth * 10; // Go to the next depth (of the power of 10)
                                              int nextN = n - remainder; // Remove the remainder from the input `n`
                                              // Do a recursive call with these next `n` and `depth`
                                              String resultRecursiveCall = g(nextN, nextDepth);
                                              if(remainder != 0) // If the remainder was not 0:
                                              // Append a " + " and this remainder to the result
                                              resultRecursiveCall += " + " + remainder;

                                              return resultRecursiveCall; // And return the result
                                              else // Else:
                                              return Integer.toString(n); // Simply return input `n` as result



                                              String f(int n) // Second method so we can accept just integer `n`
                                              return g(n, 1); // Which will call the recursive call with parameters `n` and 1



                                              The second method is so we can call the method with just a single input n. For example:



                                              String result = f(70304);


                                              Which will result in the String 70000 + 300 + 4.



                                              Try it online.




                                              To explain a bit more in depth of what this recursive method does, let's just do a step-by-step for the input 70304:



                                              1. In the first recursive iteration: n=70304, depth=1, remainder=70304%1 = 0.

                                                • Since depth < n is truthy, it will do a recursive call with 70304-0 and 1*10

                                                • And since remainder is 0, it will append nothing more to the result


                                              2. In the second recursive iteration: n=70304, depth=10, remainder=70304%10 = 4.

                                                • Since depth < n is still truthy, it will do a recursive call with 70304-4 and 10*10

                                                • And since remainder is 4, it will append a " + " and this 4 to the result


                                              3. In the third recursive iteration: n=70300, depth=100, remainder=70300%100 = 0.

                                                • Since depth < n is still truthy, it will do a recursive call with 70300-0 and 100*10

                                                • And since remainder is 0, it will append nothing more to the result


                                              4. In the fourth recursive iteration: n=70300, depth=1000, remainder=70300%1000 = 300.

                                                • Since depth < n is still truthy, it will do a recursive call with 70300-300 and 1000*10

                                                • And since remainder is 300, it will append a " + " and this 300 to the result


                                              5. In the fifth recursive iteration: n=70000, depth=10000, remainder=70000%10000 = 0.

                                                • Since depth < n is still truthy, it will do a recursive call with 70000-0 and 10000*10

                                                • And since remainder is 0, it will append nothing more to the result


                                              6. In the sixth recursive iteration: n=70000, depth=100000, remainder=70000%100000 = 70000.

                                                • Since now depth < n is falsey, it won't do any more recursive calls, but instead return the current n (which is 70000).


                                              And since these were all recursive calls, we should actually look at it backwards for the result, so it will result in 70000 + 300 + 4.



                                              So in general:



                                              • The depth < n if-check is to see when we are done with the recursive calls.

                                              • The g(n-remainder, depth*10) will remove the digits we've already output in a previous recursive iteration, and goes to the next 10k power in the next recursive iteration

                                              • The remainder != 0 if-check determines if the number we want to append was not a 0





                                              share|improve this answer












                                              This is also possible to do recursively. Here an example implementation:



                                              String g(int n, int depth) // Recursive method with 2 int parameters & String return-type
                                              int remainder = n % depth; // The current recursive remainder
                                              if(depth < n) // If we aren't done with the number yet:
                                              int nextDepth = depth * 10; // Go to the next depth (of the power of 10)
                                              int nextN = n - remainder; // Remove the remainder from the input `n`
                                              // Do a recursive call with these next `n` and `depth`
                                              String resultRecursiveCall = g(nextN, nextDepth);
                                              if(remainder != 0) // If the remainder was not 0:
                                              // Append a " + " and this remainder to the result
                                              resultRecursiveCall += " + " + remainder;

                                              return resultRecursiveCall; // And return the result
                                              else // Else:
                                              return Integer.toString(n); // Simply return input `n` as result



                                              String f(int n) // Second method so we can accept just integer `n`
                                              return g(n, 1); // Which will call the recursive call with parameters `n` and 1



                                              The second method is so we can call the method with just a single input n. For example:



                                              String result = f(70304);


                                              Which will result in the String 70000 + 300 + 4.



                                              Try it online.




                                              To explain a bit more in depth of what this recursive method does, let's just do a step-by-step for the input 70304:



                                              1. In the first recursive iteration: n=70304, depth=1, remainder=70304%1 = 0.

                                                • Since depth < n is truthy, it will do a recursive call with 70304-0 and 1*10

                                                • And since remainder is 0, it will append nothing more to the result


                                              2. In the second recursive iteration: n=70304, depth=10, remainder=70304%10 = 4.

                                                • Since depth < n is still truthy, it will do a recursive call with 70304-4 and 10*10

                                                • And since remainder is 4, it will append a " + " and this 4 to the result


                                              3. In the third recursive iteration: n=70300, depth=100, remainder=70300%100 = 0.

                                                • Since depth < n is still truthy, it will do a recursive call with 70300-0 and 100*10

                                                • And since remainder is 0, it will append nothing more to the result


                                              4. In the fourth recursive iteration: n=70300, depth=1000, remainder=70300%1000 = 300.

                                                • Since depth < n is still truthy, it will do a recursive call with 70300-300 and 1000*10

                                                • And since remainder is 300, it will append a " + " and this 300 to the result


                                              5. In the fifth recursive iteration: n=70000, depth=10000, remainder=70000%10000 = 0.

                                                • Since depth < n is still truthy, it will do a recursive call with 70000-0 and 10000*10

                                                • And since remainder is 0, it will append nothing more to the result


                                              6. In the sixth recursive iteration: n=70000, depth=100000, remainder=70000%100000 = 70000.

                                                • Since now depth < n is falsey, it won't do any more recursive calls, but instead return the current n (which is 70000).


                                              And since these were all recursive calls, we should actually look at it backwards for the result, so it will result in 70000 + 300 + 4.



                                              So in general:



                                              • The depth < n if-check is to see when we are done with the recursive calls.

                                              • The g(n-remainder, depth*10) will remove the digits we've already output in a previous recursive iteration, and goes to the next 10k power in the next recursive iteration

                                              • The remainder != 0 if-check determines if the number we want to append was not a 0






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered 18 hours ago









                                              Kevin Cruijssen

                                              3,97873680




                                              3,97873680



























                                                   

                                                  draft saved


                                                  draft discarded















































                                                   


                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52202986%2fjava-number-in-expanded-form%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest













































































                                                  Comments

                                                  Popular posts from this blog

                                                  Long meetings (6-7 hours a day): Being “babysat” by supervisor

                                                  Is the Concept of Multiple Fantasy Races Scientifically Flawed? [closed]

                                                  Confectionery