Largest among two number which don't have small number in java

You are given with two different numbers and you have to find the largest number which don’t have the smallest number(1 digit number) and the number must not greater than the larger number.

Let's go through to the steps.

  • Step - 1 Ask user for two different number.
  • Step - 2 Create a variable which hold the last position where the smallest number occurs in the largest number.
  • Step - 3 Find the Maximum and Minimum number.
  • Step - 4 Create an array of size length. Here length is the size of largest number.
  • Step - 5 Store the individual digit of largest number in the array.
  • Step - 6 Replace the largest digit by one less than the smallest digit and hold the last changed position.
  • Step - 7 If changedPosition is changed then replace the next position digits by 8 or 9. (8 if smallest number is equal to 9 and by 9 if smallest number is not equal to 9).
  • Step - 8 Print the newly generated number.


Code for Getting the largest number among two numbers which don't have small number :

package com.missTechy; import java.util.Scanner; public class LargestOfTwoNumber { public static void main(String[] args) { // Ask the user for two numbers. System.out.println("Enter two numbers :: "); // getting two number from the user. Scanner scanner = new Scanner(System.in); int first = scanner.nextInt(); int second = scanner.nextInt(); // Use this variable in order to know where the smallest number digit exist in the greatest number. int changedPosition = -1; scanner.close(); // Find the maximum and minimum of the two number. // So that we get to know which number to be subtracted from the largest. int largest = Math.max(first, second); int smallest = Math.min(first, second); // getting the length of largest number. int length = String.valueOf(largest).length(); // create an array of of size 'length' to store the individual digit of largest number. int[] digits = new int[length]; // getting individual digit of the largest number and store them in array. for(int i = 0 ; i < length ; i++) { if(largest > 0) { digits[i] = largest % 10 ; largest = largest / 10; } } // replace the largest number digit by smallest number and keep the changed position. for(int j = 0 ; j< digits.length ; j++) { if(digits[j] == smallest) { digits[j] = (smallest-1); changedPosition = j; } } // if any of the digit is changed then replace the next position digits accordingly. if(changedPosition > -1) { for(int j = 0 ; j< changedPosition ; j++) { if(smallest == 9) { digits[j] = 8; } else { digits[j] = 9; } } } // pint the new generated number. for(int j = (digits.length - 1) ; j >= 0 ; j--) { System.out.print(digits[j]); } } }

Output 1 :

Output 2 :

Output 3 :

Post a Comment

1 Comments