- Java online compiler
- Taking inputs (stdin)
- Adding dependencies
- About Java
- Syntax help
- Variables
- Loops
- 1. If Else:
- 2. Switch:
- 3. For:
- 4. While:
- 5. Do-While:
- Classes and Objects
- How to create a Class:
- Example:
- How to create a Object:
- How to define methods in a class:
- Collections
- Advantages:
- How to Write Number in Expanded Form in Java
- The solution in Java code#
- Test cases to validate our solution#
- Top Related Articles
- Java — number in expanded form
- Asia
- People also ask
- 6 Answers
- Eran
- ABHISHEK SHUKLA
- MBo
- tobias_k
- Imago
Java online compiler
Write, Run & Share Java code online using OneCompiler’s Java online compiler for free. It’s one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler’s Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.
Taking inputs (stdin)
OneCompiler’s Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).
import java.util.Scanner; class Input < public static void main(String[] args) < Scanner input = new Scanner(System.in); System.out.println("Enter your name: "); String inp = input.next(); System.out.println("Hello, " + inp); >>
Adding dependencies
OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies
apply plugin:'application' mainClassName = 'HelloWorld' run < standardInput = System.in >sourceSets < main < java < srcDir './' >> > repositories < jcenter() >dependencies < // add dependencies here as below implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9' >
About Java
Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world’s number one server programming language with a 12 million developer community, 5 million students studying worldwide and it’s #1 choice for the cloud development.
Syntax help
Variables
short x = 999; // -32768 to 32767 int x = 99999; // -2147483648 to 2147483647 long x = 99999999999L; // -9223372036854775808 to 9223372036854775807 float x = 1.2; double x = 99.99d; byte x = 99; // -128 to 127 char x = 'A'; boolean x = true;
Loops
1. If Else:
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) < // code >else < // code >
2. Switch:
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
3. For:
For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.
for(Initialization; Condition; Increment/decrement) < //code >
4. While:
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
5. Do-While:
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
Classes and Objects
Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.
How to create a Class:
class keyword is required to create a class.
Example:
How to create a Object:
How to define methods in a class:
public class Greeting < static void hello() < System.out.println("Hello.. Happy learning!"); >public static void main(String[] args) < hello(); >>
Collections
Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.
Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:
This framework also defines map interfaces and several classes in addition to Collections.
Advantages:
- High performance
- Reduces developer’s effort
- Unified architecture which has common methods for all objects.
How to Write Number in Expanded Form in Java
You will be given a number and you will need to return it as a string in Expanded Form.
Challenge.expandedForm(12); // Should return "10 + 2" Challenge.expandedForm(42); // Should return "40 + 2" Challenge.expandedForm(70304); // Should return "70000 + 300 + 4"
NOTE: All numbers will be whole numbers greater than 0.
The solution in Java code#
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(); > >
import java.util.LinkedList; public class Challenge < public static String expandedForm(int num) < LinkedListexpandedList = 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); > >
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(" + ")); > >
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)); >>
Top Related Articles
- Is a Number Prime in Java
- How to Calculate Minutes to Midnight in Java
- How to get the Sum of the First nth Term of a Series in Java
- How to Keep up the Hoop in Java
- Will there be Enough Space in Java
- How to Swap Node Pairs In Linked List in Java
- How to Solve ‘Finding Neo’ in Java
- How to Solve a Pandigital Sequence in Java
- How to Calculate Transport on Vacation in Java
- Playing with the letter ‘E’ in Java
Java — number in expanded form
My function works for first and second case, but with 70304 it gives this:
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.
Asia
People also ask
Go through the below steps to write the numbers in expanded form: Step 1: Get the standard form of the number. Step 2: Identify the place value of the given number using the place value chart. Step 3: Multiply the given digit by its place value and represent the number in the form of (digit × place value).
6 Answers
You should be adding ‘0’s to str[i] , not str[j] :
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(",", " +");
answered Oct 14 ’22 23:10
Eran
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; > >
ABHISHEK SHUKLA
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
MBo
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
tobias_k
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; Listl = new ArrayList(); 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; >
Imago
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:
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 :
- 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
- 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
- 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
- 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
- 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
- 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 .
answered Oct 15 ’22 01:10