题解 | #[NOIP1999]回文数#
[NOIP1999]回文数
https://www.nowcoder.com/practice/a432eb24b3534c27bdd1377869886ebb
#include <algorithm> #include <cmath> #include <iostream> using namespace std; long BaseConverseToDec(string num, int base) { //将base进制的字符串格式数字转换成十进制数字 string digits = "0123456789ABCEF"; long temp = 0; for (int j = 0; j < num.length(); j++) { for (int i = 0; i < digits.length(); i++) { if (digits[i] == num[j]) { temp += i * pow(base, num.length() - j - 1); } } } return temp; } string DecConverseToBase(long decimal, int base) { //将十进制数字转换成字符串格式数字 string digits = "0123456789ABCEF"; string result = ""; while (decimal > 0) { int remainder = decimal % base; result = digits[remainder] + result; decimal /= base; } return result.empty() ? "0" : result; } string AddNumOutcome(string num, int base) //将字符串格式数字相加,并输出相应进制的字符串数 字 { long temp1 = BaseConverseToDec(num, base); reverse(num.begin(),num.end()); long temp2 = BaseConverseToDec(num, base); return num = DecConverseToBase(temp1+temp2,base); } bool IsTheSame(string num, int base) //判断,反转结果是否为回文 { string temp = num; reverse(temp.begin(), temp.end()); if(num == temp) return true; else return false; } int main() { string num; int base; cin >> base >> num; int count = 0; while(count < 31) { count++; if(!IsTheSame(num, base)) num = AddNumOutcome(num,base); //当相加结果不为回文时,将相加结果 覆盖原值,再进行处理 else break; } if(count < 31) cout << "STEP=" << count - 1 << endl; else cout << "Impossible!" << endl; return 0; } // 64 位输出请用 printf("%lld")