我正在嘗試撰寫一個程式,它可以找到最接近用戶輸入整數的回文
例如:輸入98 -> 輸出101 輸入1234 -> 輸出1221
我知道我必須將整數轉換為字串并比較兩半,但我很難開始撰寫代碼
我將不勝感激任何幫助!
謝謝!
uj5u.com熱心網友回復:
我認為這是一個可以接受的解決方案:
#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';
}
這也支持帶減號 ( '-') 的數字。希望這能解決您的問題。但請在使用前進行測驗。
uj5u.com熱心網友回復:
對于十進制?還是二進制?我會先把它轉換成一個字串,然后同時從前面和后面回圈,直到它到達中間,比較字符。
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 等)來完成,然后您不需要將其轉換為字串,但您必須自己弄清楚。
這只是為了找到回文,但是回圈數字并檢查每個也是微不足道的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360351.html
