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++
#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