write a program in Java to input a number and print the number in expanded form
Answers
Answer:
Here's the required answer
SOLUTION.
Here comes my approach for the problem.
import java.util.*;
public class ExpandedForm{
public static void main(){
System.out.print("Enter a number: ");
int n=(new Scanner(System.in)).nextInt();
if(n>-1&&n<=10)
System.out.println("Expanded Form: "+n);
else{
String s="",zeros="";
for(;n!=0;n/=10){
int remainder=n%10;
if(remainder!=0)
s=remainder+zeros+"+"+s;
zeros+="0";
}
s=s.substring(0,s.length()-1);
System.out.println("Expanded form: "+s);
}
}
}
SAMPLE I/O.
Enter a number: 99
Expanded form: 90+9
Enter a number: 98
Expanded form: 90+8
Enter a number: 49
Expanded form: 40+9
Enter a number: 58
Expanded form: 50+8
Enter a number: 2201
Expanded form: 2000+200+1
Enter a number: 440001
Expanded form: 400000+40000+1
Enter a number: 5604101
Expanded form: 5000000+600000+4000+100+1
Enter a number: 2
Expanded Form: 2
Enter a number: 1
Expanded Form: 1
Enter a number: 0
Expanded Form: 0
See the attachment for verification.