描述
Alice is solving math problems these days. She is interested in a problem called ‘palindrome number’.
If we read a number forward and backward as the same, then it is called palindrome number.
Alice wonder, that given a N-based number M, can you add the number and the reverse of it, to derive a palindrome number?
For example: Given a decimal number 56, adding 56 and 65 (the reverse of 56) can derive 121, which is a palindrome number.
Moreover: As for decimal number 87:
STEP1:87+78 = 165STEP2:165+561 = 726
STEP3:726+627 = 1353STEP4:1353+3531 = 4884
The step above refers to N-based addition. The above example makes four additions to derive palindrome number 4884.
输入
There is only one test case. The first line contains two numbers N (N∈{2,10,16}) and M, regarding N-based number M.
输出
If making 30 steps (inclusive) or less can derive a palindrome number, print the minimum steps count. Otherwise, output ‘Impossible!’.
输入样例 1
10
87
输出样例 1
STEP=4
来源
NEEPU 13th ACM
代码
#include <cstdio>
#include <cstdlib>
using namespace std;
long long ced;
bool ifPalindrome(long long n, long long dec){
long long a = 0, b = dec;
while(b > 0){ // 这里判断是否是回文数
a = a * n + b % n;
b /= n;
}
if(a == dec) return 0;
else{
ced = a;
return 1;
}
}
int main(){
long long n, dec;
int count = 0;
char m[1000], *stop;
scanf("%lld %s", &n, m);
dec = strtol(m, &stop, n); // 先用strtol函数把数转换成十进制
if(n == 2 || n == 10 || n == 16){
while(ifPalindrome(n, dec)){
dec += ced;
count++;
if(count > 30) break;
}
}
if(count <= 30) printf("STEP=%d", count);
else printf("Impossible!");
return 0;
}