Search code examples
c++integerpalindrome

How to find the closest palindrome to an integer?


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!


Solution

  • 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.