如何找到最接近整数的回文?

How to find the closest palindrome to an integer?

我正在尝试编写一个程序,它可以找到最接近用户输入整数的回文

例如: 输入 98 -> 输出 101 输入 1234 -> 输出 1221

我知道我必须将整数转换为字符串并比较两半,但我很难开始编写代码

如有任何帮助,我将不胜感激!

谢谢!

我认为这是一个可以接受的解决方案:


#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';
}

这也支持带负号 ('-') 的数字。希望这能解决您的问题。但请先测试再使用。

十进制?还是二进制? 我会先把它转换成一个字符串,然后同时从前面和后面循环,直到它到达中间,比较字符。

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;
}

请原谅任何语法错误,我的平板电脑上没有编译器,但任何错误都应该很容易修复。 您也可以使用模数 (num % 10, (num % 100)/10 etc.) 来完成它,然后您不需要将它转换为字符串,但您必须自己弄清楚。

这只是为了找到回文,但循环数字并检查每个数字也是微不足道的。