Palindrome Solution [Easy]

Problem

A simple recursive method to generate a numeric palindrome from any number is to reverse its digits and add it to the original. If the sum is not a palindrome (which means, it is not the same number from left to right and right to left), repeat this procedure. For example for 195:

195 + 951 = 786
786 + 687 = 1473
1473 + 3741 = 5214
5214 + 4125 = 9339 – Resulting palindrome

Your task is to write a program that gives the resulting palindrome and the number of iterations (additions) to compute it.

Codechef Problem Link

Input

The first line will have a number N with the number of test cases, the next N lines will each have a number P to compute its palindrome

Output

For each of the N numbers you will have to write a line with the minimum number of iterations (additions) to get to the palindrome and the resulting palindrome separated by one space.

Constraints

  • 1 <= N ≤ 2000
  • 1 <= P ≤ 4,294,967,295

Sample Input

3
195
265
750

Sample Output

4 9339
5 45254
3 6666

Solution

//
//  main.cpp
//  Palindrome
//
//  Created by Himanshu on 19/02/22.
//

#include <iostream>
using namespace std;
typedef long long ll;

ll reverseNum (ll num) {
    ll revnum=0, dgt;
    
    while(num>0) {
        dgt = num%10;
        num = num/10;
        revnum = revnum*10+dgt;
    }
    
    return revnum;
}

int main() {
    int T;
    ll a, b, sum, sumTemp;
    
    cin>>T;
    
    while (T--) {
        int ctr = 1;
        
        cin>>a;
        
        b = reverseNum(a);
        sum = a+b;
        sumTemp = reverseNum(sum);
        
        while (sumTemp != sum) {
              a = sum;
              b = sumTemp;
              sum = a+ b;
              sumTemp = reverseNum(sum);
              ctr++;
        }
        
        cout<<ctr<<" "<<sum<<endl;
    }
    return(0);
}

Leave a Reply