Tuesday, April 23, 2024
HomeSoftware EngineeringWrite Quantity in Expanded Kind in Java

Write Quantity in Expanded Kind in Java


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 entire numbers higher than 0.

The answer in Java code

Possibility 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();
    }
}

Possibility 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);
    }
}

Possibility 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+"))
      .accumulate(becoming a member of(" + "));
  }
}

Check circumstances to validate our answer

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)); 
     }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments