Check if a number is a Mystery Numbers in C++


Here we will see how to check whether a number is Mystery number or not. A Mystery number is a number that can be represented by sum of two numbers, and the numbers re reverse of each other. Let us see the code to get better idea. We have to check all pairs and find the decision.

Example

 Live Demo

#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;
}
int main() {
   int num = 121;
   if(isMysteryNumber(num)){
      cout << "\n" << num << " is a Mystery number";
   }else{
      cout << " is not a Mystery number";
   }
}

Output

29 92
121 is a Mystery number

Updated on: 27-Sep-2019

495 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements