How to Write Number in Expanded Form in Java

The challenge

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

Examples:

Challenge.expandedForm(12); // Should return "10 + 2" Challenge.expandedForm(42); // Should return "40 + 2" Challenge.expandedForm(70304); // Should return "70000 + 300 + 4"
Code language: Java (java)

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

The solution in Java code

Option 1:

public class Challenge { 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(); } }
Code language: Java (java)

Option 2:

import java.util.LinkedList; public class Challenge { public static String expandedForm(int num) { LinkedList<String> expandedList = new LinkedList<>(); int digit; int multiplier = 1; while (num > 0) { digit = (num % 10) * multiplier; if (digit != 0) expandedList.push(Integer.toString(digit)); num /= 10; multiplier *= 10; } return String.join(" + ", expandedList); } }
Code language: Java (java)

Option 3:

import java.util.stream.IntStream; import static java.util.stream.Collectors.joining; public class Challenge { public static String expandedForm(int num) { var ns = ""+num; return IntStream.range(0, ns.length()) .mapToObj(i -> ns.charAt(i) + "0".repeat(ns.length() - 1 - i)) .filter(e -> !e.matches("0+")) .collect(joining(" + ")); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest { @Test public void testSomething() { assertEquals("10 + 2", Challenge.expandedForm(12)); assertEquals("40 + 2", Challenge.expandedForm(42)); assertEquals("70000 + 300 + 4", Challenge.expandedForm(70304)); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments