In: Computer Science
Write a recursive a Java code that checks if a number is
Palindrome. A
palindrome number is a number that reads the same from beginning to
end and
from end to beginning, in other words, a palindrome number remains
the same
when its digits are reversed. For example, 13431 is a palindrome
number. 2332
is another one. (Note: Your algorithm should define and work with
an integer
number)
The functionality of your code should be commented to explain what
you do in
each part of the code.
You need to run your code for the following test cases and show the
result:
1) 0 (output:
yes)
2) 1234554321 (output: yes)
3) 123454321 (output: yes)
4) 1221 (output: yes)
5) 1234 (output:
no)
6) 7676 (output: no)
7) -121 (output: yes)
8) -456 (output: no)
What is the time complexity of your algorithm? Cleary justify
your
answer.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner s=new
Scanner(System.in);
int num=s.nextInt();//reading
number
int temp,res=0;
if(num<0)//if it is negative
make positive
num=-num;
temp=num;//assigning to temparory
variable
while(temp!=0)
{
res=(res*10)+temp%10;//making it
reverse
temp=temp/10;
}
if(res==num)//checking original and
result number
{
System.out.println("output:yes");
}
else
System.out.println("output:No");
}
}
Time Complexity
The time complexity for this one is O(log n) because we are doing num%10 && num/10. so, these type of Operations gives log n complexity and remaining statements are considered constant 1 and finally it gives O(log n) complexity.