In this tutorial, we will write a Java program to check if a number is a Mystery Number. Before that, we may go through the following topic in java.
A mystery number is a number that can be expressed as the sum of two numbers and those two numbers should be the reverse of each other. It lies between 22 to 198, i.e. 22<=N<=198.
Example:
132 = 93 + 39
154 = 68 + 86
176 = 79 + 97
Program to check Mystery Number in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import java.util.Scanner; public class Main { static int reverseFunction(int n) { String str = Integer.toString(n); String string = ""; for (int i = str.length() - 1; i >= 0; i--) string = string + str.charAt(i); int revResult = Integer.parseInt(str); return revResult; } static boolean isMystery(int num) { for (int i = 1; i <= num / 2; i++) { int j = reverseFunction(i); if (i + j == num) { System.out.println(i + " " + j); System.out.println(num + " is a mystery number."); return true; } } System.out.println(num + " is NOT a mystery number."); return false; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int num = sc.nextInt(); isMystery(num); } } |
Output:
Enter a number: 132
66 66
132 is a mystery number.