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 the 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 :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(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));
} else if (c == 'l') {
System.out.println("Closest number : " + findClosestNumber(no, digit, false));
} else {
System.out.println("Please provide a valid answer !! ");
}
}
static int findClosestNumber(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;
}
static boolean isValidNumber(int no, Character digit) {
return Integer.toString(no).indexOf(digit) == -1;
}
}
Examples :
Enter a number :
133
Enter the digit :
1
Do you want to look for a number that is larger or smaller than 133 ? Please use 'g' for greater than or'l' for less than
l
Closest number : 99
Enter a number :
23567
Enter the digit :
4
Do you want to look for a number that is larger or smaller than 23567 ? Please use 'g' for greater than or'l' for less than
g
Closest number : 23568
Similar tutorials :
- Java program to find all strong numbers in a range
- Java program to find Harshad or Niven number from 1 to 100
- Java program to extract all numbers from a string
- Java program to check if all digits of a number are in increasing order
- Java program to find three numbers in an array with total sum zero
- Java program to check if a number is a buzz number or not