Write Number in Expanded Form

Write Number in Expanded Form

مساله:

عدد را بر اساس فرم منبسط شده (Expanded) نمایش دهید.

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

Description:

Write Number in Expanded Form

You will be given a number and you will need to return it as a string in Expanded Form. For example:

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

NOTE: All numbers will be whole numbers greater than 0.


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

public class Kata
{
    public static String expandedForm(int num)
    {
      List<Integer> list = new ArrayList<Integer>();
    String[] arr = (""+num).split("");
    int count = arr.length - 1;
    for (String str : arr) {
      Double n = Integer.parseInt(str) * Math.pow(10, count--);
      if (n > 0) list.add(n.intValue());
    }
    return StringUtils.join(list, " + ");
    }
}
public class Kata
{
    public static String expandedForm(int num)
    {
        String outs = "";
        for (int i = 10; i < num; i *= 10) {
            int rem = num % i;
            outs = (rem > 0) ? " + " + rem + outs : outs;
            num -= rem;
        }
        outs = num + outs;
        
        return outs;
    }
}
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Kata
{
  public static String expandedForm(int num)
    {
        return IntStream.range(0, String.valueOf(num).length())
                .mapToObj(x -> String.valueOf( Character.getNumericValue(String.valueOf(num).charAt(x) ) * (int)Math.pow(10, String.valueOf(num).substring(x).length()-1)))
                .filter(x -> !x.equals("0"))
                .collect(Collectors.joining(" + "));
    }
}
public class Kata
{
    public static String expandedForm(int num)
    {
      StringBuffer res = new StringBuffer();
      int d = 1;
      while(num > 0) {
        int nextDigit = num % 10;        
        num /= 10;
        if (nextDigit > 0) {
          res.insert(0, d * nextDigit);
          res.insert(0, " + ");
        }
        d *= 10;
      }
      
      return res.substring(3).toString();
    }
}

دیدگاهتان را بنویسید