Java Tutorial : Find closest number to a given number without a given digit
Java program to find closest number to a Given number without a given digit :
This program will find closest number to a user given number that should not contain a user input digit.
Result number can be less than or greater than the given number.
e.g. Closest number greater than 123 without containing 3 is 124 and smaller than 123 without containing 3 is 122.
Using Scanner class, we will get the number, digit and greater than/ less than informations from the user.
The digit is scanned as a character.
Using a for loop, we will scan all digits one by one.
To check if the character is in the digit , we are using Integer.toString(no).indexOf(digit). If the digit is not in the number, it will return -1.
Scan one by one and test each number.
Program :
importjava.util.Scanner;publicclassMain{publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);int no;Character digit;Character c;System.out.println("Enter a number : ");
no = sc.nextInt();System.out.println("Enter the digit : ");
digit = sc.next().charAt(0);System.out.println("Do you want to look for a number that is larger or smaller than "+ no +" ? Please use "+"\'g\' for greater than or"+"\'l\' for less than ");
c = sc.next().charAt(0);if(c =='g'){System.out.println("Closest number : "+findClosestNumber(no, digit,true));}elseif(c =='l'){System.out.println("Closest number : "+findClosestNumber(no, digit,false));}else{System.out.println("Please provide a valid answer !! ");}}staticintfindClosestNumber(int no,Character digit,boolean greaterThan){if(greaterThan){for(int i = no +1; i > no; i++){if(isValidNumber(i, digit)){return i;}}}else{for(int i = no -1; i >0; i--){if(isValidNumber(i, digit)){return i;}}}return-1;}staticbooleanisValidNumber(int no,Character digit){returnInteger.toString(no).indexOf(digit)==-1;}}
Examples :
Enter a number :133Enter the digit :1Do you want tolookfor a number that is larger or smaller than 133?Please use 'g'for greater than or'l'for less than
l
Closest number :99Enter a number :23567Enter the digit :4Do you want tolookfor a number that is larger or smaller than 23567?Please use 'g'for greater than or'l'for less than
g
Closest number :23568