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
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework