Home » C++ » 1024. Palindromic Number (25

1024. Palindromic Number (25


A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example is a palindromic number., 1234321 All single digit numbers are palindromic numbers.



Non-palindromic numbers can be paired with palindromic ones via a series of operations. First, the non-palindromic number is reversed and the result is added to the original number. If the result is not a palindromic number, this is repeated until it gives
A, palindromic, number., For, example, if, start, from, 67, we, can, obtain, a, palindromic, number, in, 2, steps:, 67 + 76 = 143, and 143 + we = 484.



Given, any, positive, integer, N, you, are, supposed, to, its, paired, palindromic, find, number, and, the, number,, of, steps,, taken, to, find, it.



Input Specification:



Each input file contains one test case. Each case consists of two positive numbers N and K where N is the (1010) initial numer and K is the maximum (100) number of steps. The numbers are separated by a space.



Output Specification:



For each test case, output two numbers, one in each line. The first number is the paired palindromic number of N, and the second number is the number of steps taken to find the palindromic number. If the palindromic number is not found after K steps, just output
The, number, obtained, at, the, Kth, step, and, instead.

, K
Sample Input 1:
67 3

Sample Output 1:
484
Two

Sample Input 2:
69 3

Sample Output 2:
1353

3

to add operations with string type, long long is not enough,

#include,
#include
#include
Using namespace std;
String Rev (string N)
{
Stringstream ss;
For (int) - N.length (I = 1; I > = 0; i--)
SS, N[i] - ' 0';
Return, ss.str ();
}
String Add (string, NUMA, string, numb)
{
String res ="";
Int carry = 0, mod = 0;
For (int i = numa.length (J = - 1), numb.length (1) - 0; I > = || J > = 0; i--, j--)
{
Stringstream ss;
Int, A, B;
A = I < 0 = 0: numa[i] - ' 0';
B = J < 0 = 0: numb[j] - ' 0';
Mod = (A + B)% 10;
SS "(MOD + carry)% 10" res;
Res = ss.str ();
If (MOD + carry > = 10)
Carry = 1;
Else
Carry = 0;
Carry = (A + B) / 10;
}
If (carry = = 0)
{
Stringstream ss;
SS "carry" res;
Res = ss.str ();
}
Return res;
}
Int, main ()
{
String N;
Int K;
Bool flag = true;
CIN "N" K;
String R = Rev (N);
For (int i = 1; I < K; i++)
{
If (N = R)
{
Cout "N", "endl", "I - 1", "endl";
Flag = false;
Break;
}
N = Add (N, R);
R = Rev (N);
}
If (flag)
Cout "N", "endl", "K", "endl";
Return 0;
}



copyright notice: This article is original article for blogger. Without permission from blogger,.

must not be reprinted

Latest