【问题标题】:How to find the closest palindrome to an integer?如何找到最接近整数的回文数?
【发布时间】:2021-11-18 19:40:17
【问题描述】:

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

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

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

我将不胜感激!

谢谢!

【问题讨论】:

  • 到目前为止你有什么?
  • 您将如何手动执行此操作?最接近 12 的回文数是多少? 112? 1222? 1299? 1000?你是怎么找到每一个的?
  • 知道是成功的一半。
  • “最接近”是什么意思?
  • 最接近 98 的回文数是 99,而不是 101!!!

标签: c++ integer palindrome


【解决方案1】:

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


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

这也支持带减号 ('-') 的数字。希望这能解决您的问题。但请在使用前进行测试。

【讨论】:

    【解决方案2】:

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

    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 等),然后您不需要将其转换为字符串,但您必须自己弄清楚。

    这只是为了找到回文,但循环数字并检查每个数字也很简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多