Reverse and Add Palindrome

Moderate
0/80
0 upvote

Problem statement

You are given a non-negative integer N. Your task is to apply the "reverse and add" process to find a resulting palindrome.

The process is as follows:

1)Take the number N.


2)Reverse its digits to create a new number, reversed_N.


3)Add the two numbers together: sum = N + reversed_N.


4)If sum is a palindrome, the process stops, and sum is the result.


5)If sum is not a palindrome, it becomes the new N, and the process repeats from step 1.


You must also handle two failure conditions:

  • If the process takes more than 1,000 additions to find a palindrome, it is considered a failure.


  • If at any step, the sum becomes greater than 4,294,967,295, the process also fails.


    If the process fails, you should indicate that a palindrome does not exist under these conditions.


  • Detailed explanation ( Input/output format, Notes, Images )
    Input Format:
    A single line containing the integer N.
    


    Output Format:
    If a palindrome is found, print the resulting number.
    
    If the process fails due to either the iteration limit or the value limit, print the string No palindrome exist.
    


    Note:
    A number is a palindrome if it reads the same forwards and backwards (e.g., 121, 9339).
    
    If the initial number N is already a palindrome, no additions are needed, and the output is N itself.
    
    The maximum value 4,294,967,295 is the largest number that can be stored in a standard 32-bit unsigned integer. You should use a data type that can handle numbers larger than this for intermediate calculations (e.g., long in Java, long long in C++).
    
    Sample Input 1:
    195
    


    Sample Output 1:
    9339
    


    Explanation for Sample 1:
    1.  195 + 591 = 786
    2.  786 + 687 = 1473
    3.  1473 + 3741 = 5214
    4.  5214 + 4125 = 9339 (This is a palindrome)
    


    Sample Input 2:
    196
    


    Sample Output 2:
    No palindrome exist
    


    Explanation for Sample 2:
    The number 196 is a famous Lychrel number candidate. The reverse-and-add process for 196 does not produce a palindrome within the 1,000-iteration limit.
    


    Expected Time Complexity:
    The expected time complexity is O(Iterations * log(N)), where Iterations is capped at 1000.
    


    Constraints:
    0 <= N <= 10000
    
    Time limit: 1 sec
    
    Approaches (1)
    Reverse and Add Palindrome
    Time Complexity
    Space Complexity
    Code Solution
    (100% EXP penalty)
    Reverse and Add Palindrome
    Full screen
    Console