The problem
You’ll be given a quantity and you’ll need to return it as a string in Expanded Kind.
Examples:
Problem.expandedForm(12); // Ought to return "10 + 2"
Problem.expandedForm(42); // Ought to return "40 + 2"
Problem.expandedForm(70304); // Ought to return "70000 + 300 + 4"
NOTE: All numbers shall be complete numbers higher than 0.
The answer in Java code
Choice 1:
public class Problem {
public static String expandedForm(int num) {
StringBuffer res = new StringBuffer();
int d = 1;
whereas(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();
}
}
Choice 2:
import java.util.LinkedList;
public class Problem {
public static String expandedForm(int num) {
LinkedList<String> expandedList = new LinkedList<>();
int digit;
int multiplier = 1;
whereas (num > 0) {
digit = (num % 10) * multiplier;
if (digit != 0) expandedList.push(Integer.toString(digit));
num /= 10;
multiplier *= 10;
}
return String.be a part of(" + ", expandedList);
}
}
Choice 3:
import java.util.stream.IntStream;
import static java.util.stream.Collectors.becoming a member of;
public class Problem {
public static String expandedForm(int num) {
var ns = ""+num;
return IntStream.vary(0, ns.size())
.mapToObj(i -> ns.charAt(i) + "0".repeat(ns.size() - 1 - i))
.filter(e -> !e.matches("0+"))
.gather(becoming a member of(" + "));
}
}
Check circumstances to validate our resolution
import org.junit.Check;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
@Check
public void testSomething() {
assertEquals("10 + 2", Problem.expandedForm(12));
assertEquals("40 + 2", Problem.expandedForm(42));
assertEquals("70000 + 300 + 4", Problem.expandedForm(70304));
}
}