Fascinating Number in Java

Configurare noua (How To)

Situatie

Multiplying a number by two and three separately, the number obtained by writing the results obtained with the given number will be called a fascinating number. If the result obtained after concatenation contains all digits from 1 to 9, exactly once.

In other words, we can also say that a number (n) may be a fascinating number if it satisfies the following two conditions:

  • If the given number is a 3 or more than three-digit
  • If the value getting after concatenation contains all digits from 1 to 9, exactly once.

For example, 192, 1920, 2019, 327, etc. Let’s understand the concept of fascinating numbers through an example.

Backup

  1. import java.util.*;
  2. public class FascinatingNumberExample1
  3. {
  4. public static void main(String args[])
  5. {
  6. int num, n2, n3;
  7. Scanner sc=new Scanner(System.in);
  8. System.out.print(“Enter any Number: “);
  9. num = sc.nextInt();
  10. n2 = num * 2;
  11. n3 = num * 3;
  12. //concatenating num, n2, and n3
  13. String concatstr = num + “” + n2 + n3;
  14. boolean found = true;
  15. //checks all digits from 1 to 9 are present or not
  16. for(char c = ‘1’; c <= ‘9’; c++)
  17. {
  18. int count = 0;
  19. //loop counts the frequency of each digit
  20. for(int i = 0; i < concatstr.length(); i++)
  21. {
  22. char ch = concatstr.charAt(i);
  23. //compares the character of concatstr with i
  24. if(ch == c)
  25. //incerments the count by 1 if the specified condition returns true
  26. count++;
  27. }
  28. //returns true if any of the condition returns true
  29. if(count > 1 || count == 0)
  30. {
  31. found = false;
  32. break;
  33. }
  34. }
  35. if(found)
  36. System.out.println(num + ” is a fascinating number.”);
  37. else
  38. System.out.println(num + ” is not a fascinating number.”);
  39. }
  40. }

Output 1:

Enter any Number: 327
327 is a fascinating number.

Output 2:

Enter any Number: 8975
8975 is not a fascinating number.

Solutie

Tip solutie

Permanent

Voteaza

(15 din 24 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?