Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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:

Java Basic Exercises: Find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9.

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:

Flowchart: Find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9.

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