luogu1015 回文数(NOIP1999普及组第2题)
时空限制 1000ms/125MB
题目描述
若一个数(首位不为零)从左向右读与从右向左读都一样,我们就将其称之为回文数。
例如:给定一个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(100位之内),求最少经过几步可以得到回文数。如果在30步以内(包含30步)不可能得到回文数,则输出“Impossible!”
输入
两行,分别是N,M。
输出
如果能在 30 步以内得到回文数,输出格式形如 STEP=ans
,其中 ans 为最少得到回文数的步数。
否则输出 Impossible!
。
输入样例
10 87
输出样例
STEP=4
代码
法一:数组模拟
#include<iostream>
#include<string>
#include<cstring>
#include<cctype>
using namespace std;
const int N = 150;
int r,a[N],b[N],cnt=0;
void zhuan(string s,int a[]){
memset(a,0,sizeof(int)*N);
a[0] = s.size();
for (int i=1; i<=a[0]; ++i)
if (isdigit(s[a[0]-i])) a[i]=s[a[0]-i]-48;
else a[i]=s[a[0]-i]-55;
}
bool ishw(int a[]){
for (int i=1,j=a[0]; i<j; ++i,--j)
if (a[i]!=a[j]) return false;
return true;
}
void add(int r,int a[],int b[]){
for (int i=1; i<=a[0]; ++i) b[i]=a[a[0]-i+1];
for (int i=1; i<=a[0]; ++i){
a[i] += b[i];
a[i+1] += a[i]/r;
a[i] %= r;
}
if (a[a[0]+1]) a[0]++;
}
int main(){
string s;
cin>>r>>s;
zhuan(s,a);
while (!ishw(a) && cnt<=30){
cnt++;
add(r,a,b);
}
if (cnt<=30) cout<<"STEP="<<cnt<<'\n';
else cout<<"Impossible!"<<'\n';
return 0;
}
法二:重载运算符
#include<iostream>
#include<cstring>
#include<string>
#include<cctype>
#include<algorithm>
using namespace std;
const int N = 150;
int r,cnt=0;
struct bign{
int len,d[N];
bign(){ memset(d,0,sizeof(d)); len=1; } //构造函数,默认初始化
bign(string x){ //构造函数,string初始化
memset(d,0,sizeof(d));
len = x.size();
for (int i=1; i<=len; ++i)
if (isdigit(x[len-i])) d[i]=x[len-i]-48;
else d[i]=x[len-i]-55;
}
bign operator + (const bign &b){ //重载+ 高+高
bign c; //c=结构体本身+b
c.len = max(len,b.len);
for (int i=1; i<=c.len; ++i){
c.d[i] += d[i]+b.d[i];
c.d[i+1] += c.d[i]/r;
c.d[i] %= r;
}
if (c.d[c.len+1]) c.len++;
return c;
}
bool huiwen(){ //成员函数,判断是否回文
for (int i=1,j=len; i<j; ++i,--j)
if (d[i]!=d[j]) return false;
return true;
}
bign add(){ //成员函数,颠倒后相加
bign a; //a为结构体反向
a.len = len;
for (int i=1; i<=len; ++i) a.d[i]=d[len-i+1];
*this = *this+a; //需重载高+高
return *this;
}
friend istream& operator >> (istream& input,bign &x){ //重载输入流
string s;
input>>s;
x = s;
return input;
}
};
int main(){
bign m;
cin>>r>>m; //需重载输入流
while (!m.huiwen() && cnt<=30){ //成员函数huiwen()
cnt++;
m.add(); //成员函数add()需重载 高+高 高+=高
}
if (cnt<=30) cout<<"STEP="<<cnt<<'\n';
else cout<<"Impossible!\n";
return 0;
}