Java Exercises: Find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9
Java Basic: Exercise-231 with Solution
Write a Java program to find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9. The number that can be rearranged shall start with 0 as in 00135668.
Input:
Data is a sequence of 8 numbers (numbers from 0 to 9).
Output:
The difference between the largest integer and the smallest integer.
Pictorial Presentation:

Sample Solution:
Java Code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input an integer created by 8 numbers from 0 to 9:");
String s = sc.next();
int[] num = new int[8];
for(int i=0;i<8;i++){
num[i] = Integer.valueOf(s.substring(i,i+1));
}
Arrays.sort(num);
int a = 0;
int b = 0;
int c = 1;
for(int i=0;i<8;i++){
a += num[i]*c;
b += num[7-i]*c;
c *= 10;
}
System.out.println("Difference between the largest and the smallest integer from the given integer:");
System.out.println(a-b);
}
}
Sample Output:
Input an integer created by 8 numbers from 0 to 9: 567894321 Difference between the largest and the smallest integer from the given integer: 75308643
Flowchart:

Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to replace a string "python" with "java" and "java" with "python" in a given string.
Next: Write a Java program to compute the sum of first n given prime numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
Java: ConvertInputStreamToString
Converts InputStream to a String.
public static String convertInputStreamToString(final InputStream in) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString(StandardCharsets.UTF_8.name()); }
Ref: https://bit.ly/2N1GDss
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises