PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to find the closest palindrome to an integer?

 July 21, 2022     c++, integer, palindrome     No comments   

Issue

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.



Answered By - digito_evo
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing