Ejemplo 1: programa Java para comprobar la cadena palíndromo mediante recursividad
import java.util.Scanner;
public class RecursivePalindromeJava
{
// to check if string is palindrome using recursion
public static boolean checkPalindrome(String str)
{
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length() - 1))
return checkPalindrome(str.substring(1, str.length() - 1));
return false;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string : ");
String strInput = sc.nextLine();
if(checkPalindrome(strInput))
{
System.out.println(strInput + " is palindrome");
}
else
{
System.out.println(strInput + " not a palindrome");
}
sc.close();
}
}
Ejemplo 2: programa Java para comprobar el número palíndromo mediante recursividad
// Java program to check palindrome number using recursion
public class PalindromeNumberRecursion
{
static int palindromeRecursion(int number, int temp)
{
if(number == 0)
return temp;
// storing reverse of a number
temp = (temp * 10) + (number % 10);
return palindromeRecursion(number / 10, temp);
}
public static void main(String[] args)
{
int number = 141;
int temp = palindromeRecursion(number, 0);
if(temp == number)
{
System.out.println("number is palindrome.");
}
else
{
System.out.println("number is not palindrome.");
}
}
}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)