Java program of Next Greatest number

Question:-

Write a program to find the next greatest number that can be formed using the digits in the given input number.

If the given number cannot generate the next greatest number then print the input number itselfSample Input1:

23

Sample Output1:

32

Sample Input2:

123

Sample Output2:

132

Sample Input3:

6251

Sample Output3:

6512

Code:-

Main.java

import java.util.Scanner;
import java.util.Arrays;
public class Main{
    
    static void swap(char ar[], int i, int j){
        char temp = ar[i];
        ar[i] = ar[j];
        ar[j] = temp;
    }
    
    static void findNextGreatest(char ar[], int n){
        int i;
        for(i = n -1; i > 0; i--){
            if(ar[i] > ar[i-1])
                break;
        }
        if(i == 0){
            for(int j = 0; j < ar.length; j++)
                System.out.print(ar[j]);
        }
        else{
            int x = ar[i - 1], min = i;
            for(int k = i + 1; k < n; k++){
                if(ar[k] > x && ar[k] < ar[min])
                    min = k;
            }
            swap(ar, i-1, min);
            Arrays.sort(ar, i, n);
            for(int l = 0; l < ar.length; l++)
                System.out.print(ar[l]);
        }
    }
    
    
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        char arr[] = input.toCharArray();
        findNextGreatest(arr, arr.length);
        
    }
}

Recommended:-

  1. Array square
  2. Generate number using odd digits
  3. Alternate Number Difference
  4. Next Greatest number
  5. Mark Comparison
  6. Print the characters in descending order
  7. Vowels in a fishBowl
  8. Least offer
  9. Ascending and descending order
  10. Mail Domain
  11. Count repeating words
  12. Sentence – Convert to upper and lower
  13. Count consecutive repeating characters
  14. Zig zag Array
  15. Pass and Fail Count
  16. Search a Course
  17. Average and Grade Calculation
  18. String – Find and replace the character (first occurrence)
  19. Sort the first and second half of an array
  20. Retail Shop
  21. Palindrome
  22. Numerology
  23. InitCap
  24. Array Compatiblilty
  25. Sum of the maximum and the minimum element
  26. String Concatenation
  27. Find Average Age
  28. Login
  29.  

Leave a Comment

Your email address will not be published. Required fields are marked *

x