问题描述
若一个数(首位不为零)从左向右读与从右向左读都一样,我们就将其称之为回文数。
例如:给定一个10进制数56,将56加65(即把56从右向左读),得到121是一个回文数。
又如:对于10进制数87:
STEP1:87+78 = 165 STEP2:165+561 = 726
STEP3:726+627 = 1353 STEP4:1353+3531 = 4884
在这里的一步是指进行了一次N进制的加法,上例最少用了4步得到回文数4884。
写一个程序,给定一个N(2<=N<=10或N=16)进制数M(其中16进制数字为0-9与A-F),求最少经过几步可以得到回文数。
如果在30步以内(包含30步)不可能得到回文数,则输出“Impossible!”
输入格式
两行,N与M
输出格式
如果能在30步以内得到回文数,输出“STEP=xx”(不含引号),其中xx是步数;否则输出一行”Impossible!”(不含引号)
样例输入
9
87
样例输出
STEP=6
解题思路:因为输入的数可能是十进制以上(含有字母),因此不能用int类型来存储,只能使用char类型的字符串来存储输入的数据M。
在每步操作中需要将正序的M和逆序的M相加,我定义了一个reverse函数,功能是将传递过去的字符串逆序存储到新的字符串中,并返回新字符串。
string reverse(string s)
{
string re;
int j = s.length();
int i;
for (i = 0; i < j; i++)
{
re += s[j - 1 - i];
}
return re;
}
为了计算方便,需要先将N进制的正序M和逆序后的M转为十进制。再以十进制的形式进行相加,再将相加后的结果转化为N进制。这里我定义了两个函数——NToTen和TenToN,前者是将N进制转为十进制,后者是将十进制转为N进制
//N进制转为十进制
long long NToTen(string sn, int n)
{
int len = sn.length();
if (len == 0) return 0;
string s1 = sn.substr(0, len - 1);
char ch = sn[len - 1];
int t;
if (ch <= '9') t = ch - '0';
else t = ch - 'A' + 10;
return NToTen(s1, n) * n + t;
}
//十进制转为N进制
string TenToN(long long int a, int n)
{
string s;
int ys;
char ch;
while (a / n)
{
ys = a % n;
if (ys > 9) ch = ys - 10 + 'A';
else ch = ys + '0';
s = ch + s;
a = a / n;
}
ys = a % n;
if (ys > 9) ch = ys - 10 + 'A';
else ch = ys + '0';
s = ch + s;
return s;
}
在循环进行的每步操作后需要判断相加后的数是否为回文,这里我定义了一个bool类型的函数,如果相加后的数是回文,函数返回true,否则返回false。
bool hw(string s)
{
int i, j = s.length() - 1;
for (i = 0; i < j; i++, j--)
{
if (s[i] != s[j]) return false;
}
return true;
}
整个题目的全部代码如下:
#include<iostream>
#include<string>
using namespace std;
string TenToN(long long int a, int n)
{
string s;
int ys;
char ch;
while (a / n)
{
ys = a % n;
if (ys > 9) ch = ys - 10 + 'A';
else ch = ys + '0';
s = ch + s;
a = a / n;
}
ys = a % n;
if (ys > 9) ch = ys - 10 + 'A';
else ch = ys + '0';
s = ch + s;
return s;
}
long long NToTen(string sn, int n)
{
int len = sn.length();
if (len == 0) return 0;
string s1 = sn.substr(0, len - 1);
char ch = sn[len - 1];
int t;
if (ch <= '9') t = ch - '0';
else t = ch - 'A' + 10;
return NToTen(s1, n) * n + t;
}
bool hw(string s)
{
int i, j = s.length() - 1;
for (i = 0; i < j; i++, j--)
{
if (s[i] != s[j]) return false;
}
return true;
}
string reverse(string s)
{
string re;
int j = s.length();
int i;
for (i = 0; i < j; i++)
{
re += s[j - 1 - i];
}
return re;
}
int main()
{
int n = 0;
cin >> n;
string s;
cin >> s;
int num = 0;
string rs = reverse(s);
long long sum = 0;
do
{
sum = NToTen(s, n) + NToTen(rs, n);
num++;
string t = TenToN(sum, n);
if (hw(t)) break;
else
{
s = t;
rs = reverse(s);
}
} while (num <= 30);
if (num > 30) cout << "Impossible!" << endl;
else cout << "STEP=" << num << endl;
return 0;
}