You are here : InfyTQ Archive >> InfyTQ Coding Problems
You are provided with a string of numbers, check whether it is a palindrome or not. If it is not a palindrome, then, reverse the string, add it to the original string and check again. You are required to repeat the process until it becomes palindrome. Find the length of palindromic string.
Input :
First Input : String
Output : Length of Palindrome
Sample Testcases :
I/P 1:
1
O/P 1:
1
I/P 2:
145
O/P 2:
3
Explanation :
Given string is 145, it is not a palindrome. Reversing and adding, 145+541 = 686, Hence it is a palindrome.
Solution :
def palincheck(num):
s=str(num[::-1])
if s==num:
return True
return False
n=(input())
val=0
k=0
while(True):
if(palincheck(n)):
val=len(n)
print(val)
break
else:
s1 = str(n[::-1])
k=int(n)+int(s1)
n=str(k)
palincheck(n)
It Can Be Done Like This:
S=Input()
While(S!=S[::-1]):
S=Str(Int(S)+Int(S[::-1]))
Print(len(S))
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PalindromeString {
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
long n=Long.parseLong(s);
while(!isPalin(s)){
s=””+(n+Long.parseLong(reverse(n)));
System.out.println(s);
}
System.out.println(s.length());
}
public static String reverse(long n){
String s=””+n;
String input =s;
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1 = input1.reverse();
return input1.toString();
}
public static boolean isPalin(String s){
int i=0,j=s.length()-1;
while(i<=j){
if(s.charAt(i)==s.charAt(j)){
i++;j–;
}
else{
return false;
}
}
return true;
}
}