Fascinating Number in Java
A Fascinating Number is a special number that, when multiplied by 2 and 3, and all three results are concatenated together, produces a 9-digit string that contains all digits from 1 to 9 exactly once. Zero (0) must not appear in the final combined string.
Example
Example 1: 192
Multiply the number by 1, 2, and 3:
- 192 × 1 = 192
- 192 × 2 = 384
- 192 × 3 = 576
Now concatenate them:
"192" + "384" + "576" = "192384576"
The result 192384576 contains all digits from 1 to 9 exactly once and is a valid Fascinating Number.
Example 2: 853
- 853 × 1 = 853
- 853 × 2 = 1706
- 853 × 3 = 2559
Concatenate:
"853" + "1706" + "2559" = "85317062559"
This contains more than 9 digits and does not contain digits 1–9 exactly once. So, 853 is NOT a Fascinating Number.
Java Program to Check Fascinating Number
public class FascinatingNumber {
// Function to check if a number is fascinating
static boolean isFascinating(int num) {
String concat = num + "" + (num * 2) + "" + (num * 3);
// If length is not 9, it cannot be fascinating
if (concat.length() != 9) return false;
// Check if digits 1 to 9 appear exactly once
for (char digit = '1'; digit <= '9'; digit++) {
if (concat.indexOf(digit) == -1 || concat.indexOf(digit) != concat.lastIndexOf(digit)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int num = 192;
if (isFascinating(num)) {
System.out.println(num + " is a Fascinating Number");
} else {
System.out.println(num + " is NOT a Fascinating Number");
}
}
}
Practice Challenges
- Print all Fascinating Numbers between 100 and 10,000.
- Modify the program to take user input and check the number.
- Update the program to show the concatenated result along with validation steps.