回文数

1116: 回文数

Description

若一个数(首位不为零)从左向右读与从右向左读都一样,我们就将其称之为回文数。 例如:给定一个10进制数56,将56加56(即把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,求最少经过几步可以得到回文数。如果在30步以内(包含30步)不可能得到回文数,则输出“Impossible!”

Input

输整数N和M

Output

STEP=<输出正整数s>,表示经过s步加法后可得到回文数。如果s>30,则输出Impossible!

Sample Input

9 87

Sample Output

STEP=6

HINT

Source

经过一番思考,然后自己编写代码,发现要将str 改成 int , 又要从 int 变回 str, 而且还要考虑进位问题,创建了多个int 数组 和 str 数组来存,
发现代码繁杂,果断看了别人的代码,思维如此清晰。喟叹不如。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int step = 0;
char s[100];
int n, len;
void reverse(int t[]) {
	for (int i = 0, j = len - 1; i < j; j--, i++)
	{
		swap(t[j], t[i]);
	}
}
void caculate(int t[]) {
	//reverse(t);
	for (int i = 0; i < len; i++) {
		if (t[i] >= n) {
			t[i + 1] += t[i] / n;
			t[i] %= n;
		}
	}
	while (t[len] > 0)
	{
		if (t[len] >= n) {
			t[len + 1] += t[len] / n;
			t[len] %= n;
		}
		++len;
	}
	//reverse(t);
}
bool Check() {
	int len = strlen(s);
	for (int i = 0, j = len - 1; i <j; i++, j--)
		if (s[i] != s[j])
			return false;
	return true;
}
void ArrToStr(int t[]) {
	for (int i = 0; i < len; i++) {
		if (t[i] < 10) s[i] = t[i] + '0';
		else s[i] = t[i] - 10 + 'A';
	}
	s[len] = 0;
}
void StrToArr(int t[]) {
	for (int i = 0; i < len; i++)
	{
		if (s[i] <= '9' && s[i] >= '0') t[i] = s[i] - '0';
		else t[i] = s[i] - 'A' + 10;
	}
}
void another()
{
	int t1[1000] = { 0 }, t2[1000] = { 0 };
	StrToArr(t1);
	StrToArr(t2);
	reverse(t2);
	for (int i = 0; i < len; i++)
		t1[i] += t2[i];
	caculate(t1);
	ArrToStr(t1);
}
int main() {
	while (cin >> n >> s) {
		bool Is = false;
		len = strlen(s);
		while (step <= 30) {
			if (Check()) {
				Is = true;
				break;
			}
			else another();
			step++;
		}
		if (Is)
			cout << "STEP=" << step << endl;
		else
			cout << "Impossible!" << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值