rahul alvares
rahul alvares

Reputation: 3

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 originalNumber;
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 != originalNumber) {
        System.out.println("The number is not a palindrome");
    }
}

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

Upvotes: 0

Views: 6497

Answers (4)

pbajpai
pbajpai

Reputation: 1369

If you want to learn about recursion, then you can also solve the problem above by converting the number to String, because if we have to just check whether the number is palindrome or not, then it will be very easy to solve it by first converting the number into a String (or character array). See the code below, check the isPalindrome() method, and debug it to get the recursion working.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number");
    String str = String.valueOf(sc.nextInt());
    boolean isPalin = isPalindrome(str, 0, str.length() - 1);
    if (isPalin) {
        System.out.println("The number is a palindrome");
    }
    else {
        System.out.println("The number is not a palindrome");
    }
}

private static boolean isPalindrome(String num, int i, int j) {
    if (i >= j) {
        return true;
    }
    return num.charAt(i) == num.charAt(j) && isPalindrome(num, i + 1, j - 1);
}

Upvotes: 2

κροκς
κροκς

Reputation: 590

Using global scope or static variables to perform recursion is usually an indication of lack of fully grasping how recursion should work. I suggest solving a few programming problems with trees and linked lists, those data structures are suitable for practicing and understanding recursion.

One possible solution to your problem, without converting the number to a String:

public class NumericPalindrome {

   public static void main(String args[]) {
       System.out.println(isNumericPalindrome(22)); // true
       System.out.println(isNumericPalindrome(131)); // true
       System.out.println(isNumericPalindrome(1)); // true
       System.out.println(isNumericPalindrome(9987)); // false
       System.out.println(isNumericPalindrome(1331)); // true
       System.out.println(isNumericPalindrome(-1221)); // true
       System.out.println(isNumericPalindrome(112112)); // false
   }

   public static boolean isNumericPalindrome(int n) {
       // Define how negative numbers should be handled
       if (n < 0)
          n = Math.abs(n); // or n *= -1;

       if (n < 10)
          return true;

       return isNumericPalindrome(n, n, 0);
   }

   private static boolean isNumericPalindrome(int original, int sliced, int pow) {
       if (sliced < 10)
          return sliced == original % 10;

       return isNumericPalindrome(original, sliced / 10, pow + 1) &&
              sliced % 10 == (original / (int) Math.pow(10, pow)) % 10;
   }
}

Upvotes: 0

MC Emperor
MC Emperor

Reputation: 22997

@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
}

Upvotes: 0

pjs
pjs

Reputation: 19855

Here's a solution which operates numerically rather than convert to String. It has a simple public front-end, and uses a private back-end to do the recursion to hide the state checking info that the user shouldn't need to see or know.

import java.util.Scanner;

public class PalindromeChecker {

   public static boolean isPalindrome(int number) {
      return backend(number, 0, number);
   }

   private static boolean backend(int original, int reversed, int reduced) {
      if (reversed == original) return true ;
      if (reduced < 1)          return false; 
      return backend(original, reversed * 10 + reduced % 10, reduced / 10);
   }

   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the number");
      int number = sc.nextInt();
      if (isPalindrome(number)) {
         System.out.println("The number is a palindrome");
      } else {
         System.out.println("The number is not a palindrome");
      }
      sc.close();
   }

}

In other languages, you could avoid the backend by using default values for the parameters.

Upvotes: 0

Related Questions