Home > Mobile >  How to find the closest palindrome to an integer?
How to find the closest palindrome to an integer?

Time:11-19

I'm trying to write a program which can find the closest palindrome to an user-input integer

For example: input 98 -> output 101 input 1234 -> output 1221

I know i have to transform the integer into string and compare the both halves but i have a hard time trying to start writing the code

I would appreciate any help!

Thanks!

CodePudding user response:

I think this is an acceptable solution:


#include <iostream>
#include <string>


int main( )
{
    std::string num;
    std::cout << "Enter a number: ";
    std::cin >> num;

    std::string str( num );
    bool isNegative { };
    if ( str[0] == '-' )
    {
        isNegative = true;
        str.erase( str.begin( ) );
    }

    size_t sourceDigit { };

    for ( size_t targetDigit = str.length( ) - 1; targetDigit >= str.length( ) / 2; --targetDigit,   sourceDigit )
    {
        str[ targetDigit ] = str[ sourceDigit ]; // targetDigit is any digit from right-hand side half of the str that
                                                 // needs to be modified in order to make str a palindrome.
    }

    std::cout << "The closest palindrome to " << num << " is " << ( ( isNegative ) ? "-" : "" ) << str << '\n';
}

This supports numbers with a minus sign ('-') too. Hopefully, this will solve your issue. But please test it before using it.

CodePudding user response:

For decimal? Or binary? I would convert it to a string first and then loop from the front and the back at the same time until it reaches the middle, comparing the chars.

bool isPalindrome(int num)
{
  std::stringstream ss;
  ss << num;
  std::string numStr = ss.str();
  auto from = numStr.begin();
  auto to = std::advance(numstr.end(), -1);
  auto end = numStr.end();
  while (from != end && to != end && to < from) {
    if (*from != *to) {
      return false;
    }
    std::advance(from);
    if (from == to) {
      return true;
    }
    std::advance(to, -1);
  }
  return true;
}

Excuse any syntax errors, I don't have a compiler on my tablet, but any errors should be trivial to fix. You can also do it with modulus (num % 10, (num % 100)/10 etc.), then you don't need to convert it to a string, but you will have to figure that one out yourself.

This is just for finding the palindrome, but looping around the number and checking each is also trivial.

  • Related