rahul alvares - 1 year ago 84
Java Question

# Using recursion to determine if a number is a palindrome

The objective here is to check if a number is palindrome or not using recursion. Today is my first day with recursion so as you can see the code doesn't seem very convincing.

I tried to use print statements to see what was going wrong. The first time I ran the program I input '101'.'pal_Q' and 'temp' had the same value(101) however the output was 'The number is not a palindrome'.

I wasn't sure what was wrong so I ran it again inputting 22, but it still did not work. Is something wrong with my if statements? What is the bug?

``````private static int pal_Q = 0;
private static int temp;
private static int i = 0;

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
checkPal(sc.nextInt());

if (pal_Q == temp) {
System.out.println("The number is a palindrome");
}
else if (pal_Q != temp) {
System.out.println("The number is not a palindrome");
}
}

public static int checkPal(int n) {
pal_Q *= 10;
if (i == 0) {
temp = n;
i++;
}
if (n == 0) {
return 1;
}
pal_Q+=n%10;
System.out.println("Pal_Q="+pal_Q+"...... temp ="+temp+" ........n="+n+" " +n%10);
return checkPal(n/10);
}
``````

@pbajpai21 provided an alternative solution, but I'm answering your original question.

The final value of `pal_Q` is `7370`; you only need to divide it by 10, and then your code is correct.

``````checkPal(sc.nextInt());
if (pal_Q / 10 == temp) {
// Is palindrome
}
else {
// Is not a palindrome
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download