In this tutorial, we will write a C++ program to check if a number is a Mystery Number. Before that, we may go through the following topic in C++.
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 C++
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 43 44 | #include <bits/stdc++.h> using namespace std; int revNum(int str) { string s = to_string(str); reverse(s.begin(), s.end()); stringstream ss(s); int rev = 0; ss >> rev; return rev; } bool isMysteryNumber(int n) { for (int i = 1; i <= n / 2; i++) { int j = revNum(i); if (i + j == n) { cout << i << " " << j; return true; } } return false; } //main function int main() { int num; cout << "Enter the number: "; cin >> num; if (isMysteryNumber(num)) cout << "\n" << num << " is a Mystery number"; else cout << "\n" << num << " is NOT a Mystery number"; } |
Output:
Enter the number: 154
59 95
154 is a Mystery number