Computer >> Computer tutorials >  >> Programming >> C++

Double Base Palindrome in C++ Program


In this tutorial, we are going to write a program that checks whether the given number is a palindrome in two number systems.

We have given a number and a base for another number system. We have to check whether the given number is a palindrome in the decimal number system and given number system.

Let's see the steps to solve the problem.

  • Initialize the number and number system base.

  • Check whether the given number is a palindrome in the decimal number system or not.

  • Convert the number into another number system in a string format.

  • Check whether the converted number is palindrome or not.

  • If the given number is a palindrome in both number systems, then print Yes else No.

Example

Let's see the code.

#include <bits/stdc++.h>
using namespace std;
string integer_to_string(int n, int base) {
   string str;
   while (n > 0) {
      int digit = n % base;
      n /= base;
      str.push_back(digit + '0');
   }
   return str;
}
string isDoubleBasePalidrome(int n, int k) {
   int temp = n;
   int number_reverse = 0;
   while (temp > 0) {
      number_reverse = temp % 10 + number_reverse * 10;
      temp /= 10;
   }
   if (number_reverse == n) {
      // converting to base k
      string str = integer_to_string(n, k);
      string str_copy = str;
      // reversing number in base k
      reverse(str.begin(), str.end());
      if (str == str_copy) {
         return "Yes";
      }
   }
   return "No";
}
int main() {
   int n = 313, k = 2;
   cout << isDoubleBasePalidrome(n, k) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

Yes

Conclusion

If you have any queries in the tutorial, mention them in the comment section.