- 回文数
- 2017-04-07 18:14:41 @
#include <iostream>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <sstream>
using namespace std;
int convert(char ch) {
if (isdigit(ch))
return ch - '0';
else
return 10 + 'A' - ch;
}
string add(string s1, string s2, int base) {
if (s1.length() < s2.length())
swap(s1, s2);
int maxsize = max(s1.length(), s2.length()) + 1;
int a[s1.length()], b[s2.length()], c[maxsize];
for (int i = 0; i < s1.length(); i++) a[i] = convert(s1[s1.length() - i - 1]);
for (int i = 0; i < s2.length(); i++) b[i] = convert(s2[s2.length() - i - 1]);
memset(c, 0, sizeof(c));
for (int i = 0; i < s1.length(); i++) {
c[i] += a[i];
if (i < s2.length())
c[i] += b[i];
c[i + 1] += c[i] / base;
c[i] %= base;
}
ostringstream oss;
for (int i = 0; i < maxsize; i++)
oss << c[i];
string result = oss.str();
reverse(result.begin(), result.end());
while (result[0] == '0')
result.erase(0, 1);
return result;
}
int main() {
int base;
cin >> base;
string num;
cin >> num;
bool can = false;
for (int i = 1; i <= 30; i++) {
string tmp = num;
reverse(tmp.begin(), tmp.end());
num = add(tmp, num, base);
tmp = num;
reverse(tmp.begin(), tmp.end());
if (num == tmp) {
cout << "STEP=" << i << endl;
can = true;
break;
}
}
if (!can)
cout << "Impossible!" << endl;
return 0;
}
1 条评论
-
larryzhong LV 9 @ 2017-07-25 00:06:12
呵呵
已找到第二组测试数据(十六进制):
第二组数据:
16
AC27
附改正后代码:#include <iostream> #include <cctype> #include <algorithm> #include <cstring> #include <sstream> using namespace std; int convert1(char ch) { if (isdigit(ch)) return ch - '0'; else return 10 + 'A' - ch; } char convert2(int n) { if (0 <= n && n <= 9) return '0' + n; else return 'A' + n - 10; } string add(string s1, string s2, int base) { if (s1.length() < s2.length()) swap(s1, s2); int maxsize = max(s1.length(), s2.length()) + 1; int a[s1.length()], b[s2.length()], c[maxsize]; for (int i = 0; i < s1.length(); i++) a[i] = convert1(s1[s1.length() - i - 1]); for (int i = 0; i < s2.length(); i++) b[i] = convert1(s2[s2.length() - i - 1]); memset(c, 0, sizeof(c)); for (int i = 0; i < s1.length(); i++) { c[i] += a[i]; if (i < s2.length()) c[i] += b[i]; c[i + 1] += c[i] / base; c[i] %= base; } string result = ""; for (int i = maxsize - 1; i >= 0; i--) { if (i == maxsize - 1 && convert2(c[i]) == '0') continue; result.push_back(convert2(c[i])); } return result; } int main() { int base; cin >> base; string num; cin >> num; bool can = false; for (int i = 1; i <= 30; i++) { string tmp = num; reverse(tmp.begin(), tmp.end()); num = add(tmp, num, base); tmp = num; reverse(tmp.begin(), tmp.end()); if (num == tmp) { cout << "STEP=" << i << endl; can = true; break; } } if (!can) cout << "Impossible!" << endl; return 0; }
- 1