palindrome numbers

If a number (with a non-zero leading position) reads the same from left to right as from right to left, we call it a palindrome.

For example: Given a decimal number 56, add 56 to 65 (that is, read 56 from right to left), and get 121 is a palindrome.

Another example: for the decimal number 87:

STEP1:87+78 = 165 STEP2:165+561 = 726

STEP3:726+627 = 1353 STEP4:1353+3531 = 4884

One step here refers to an N-ary addition. The above example takes at least 4 steps to get the palindrome number 4884.

Write a program, given an N (2<=N<=10, N=16) base number M (within 100 digits), find the palindrome number after at least a few steps. If it is impossible to get the number of palindromes within 30 steps (including 30 steps), output "Impossible!"

Input and output format

Input format:

 

Two lines, N and M respectively.

 

Output format:

 

STEP=ans

 

Input and output example

Input Sample #1
 
10
87
Sample output:
STEP=4
 
 
Code:

#include<iostream>
#include<string>
#define ll unsigned long long
using namespace std;

ll n = 0, k, len, nex;
string nn;
bool wow(ll a)
{
 ll s = 0;
 for (ll i = a; i; i /= k)
  s = s*k + i%k;   //倒置数字
 nex = s + a;
 return s == a;
}

ll ch(char a)   //数字转换
{
 if (a >= '0'&&a <= '9')return a - '0';
 return a - 'A' + 10;
}

int main()
{
 cin >> k >> nn;
 len = nn.size();
 for (int i = 0; i < len; i++)
  n = n*k + ch(nn[i]); // The inversion of the original number. Because
           // every number requires inversion.
 ll step;
 for (step = 0; !wow(n) && step <= 30; step++)
  n = nex; //The sum of the inverted number and the positive number
 if (step <= 30)cout << "STEP=" << step << endl;
 else cout << "Impossible!";
 return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325103756&siteId=291194637