Problem: Write a Java program to check whether a given number is a Fascinating number or not.
A Fascinating number is the number which when combined with its multiple of 2 and 3 results into a number that consists of all digits from 1 to 9 exactly once.
Example: 192
Steps to Check Fascinating number in Java:
- Input a number.
- Compute its multiple of 2 and 3.
- Concatenate the multiple calculated in the previous step with the input number.
- Count the frequency of each digit in the concatenated number.
- Check if all the counts are exactly 1.
- If so, then the input number is a fascinating number otherwise not.
Here is the Java program, which implements the above step to verify whether the input number is fascinating number or not:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//1. Input a number
System.out.println("Enter a number");
int num=in.nextInt();
//2. Compute its multiple of 2 and 3.
int mulBy2 = num*2;
int mulBy3 = num*3;
//3. Cancatenate numbers
int newNumber = 0;
newNumber += num;
newNumber = newNumber * (int)Math.pow(10,countDigits(mulBy2)) + mulBy2;
newNumber = newNumber * (int)Math.pow(10,countDigits(mulBy3)) + mulBy3;
//4. Count the frequency of each digit
int count[] = new int[10];
while(newNumber>0){
++count[newNumber%10];
newNumber = newNumber/10;
}
//5. checking if all counts are 1.
boolean flag = true;
for(int i=1; i<10; i++){
/*
*If any digit appears more than one in the concatenated number-
* then it is not a fascinating number
*/
if(count[i] != 1){
flag = false;
break;
}
}
//6. Print the result
if(flag)
System.out.println("Fascinating Number");
else
System.out.println("Non Fascinating Number");
}
//Function to return count of digits in a Number
private static int countDigits(int num){
int count=0;
while(num>0){
count++;
num=num/10;
}
return count;
}
}
Output:
Enter a number
192
Fascinating Number
Explanation:
To concatenate the multiples with the input number, we use the count of digits as follows:
//multiple of 2 192*2 = 384 (3 digits) 192*(10^3) = 192000 192000+384 = 192384 //multiple of 3 192*3 = 576 (3 digits) 192384*(10^3) = 192384000 192384000+576 = 192384576
We store the count of each digit in an array and then examine the array whether all the counts are 1 or not.
We then print the result depending on the result whether the above conditions were satisfied or not.