Introducción a Palindrome en Java

Se dice que una Cadena o un número es un palíndromo si permanece igual incluso después de que se invierte. Por ejemplo, 'MADAM' es una cadena de palíndromo ya que se escribe 'MADAM' incluso si se invierte. Pero en el caso de 'LUCKY', esta cadena no es palíndromo, ya que es 'YKCUL' cuando se invierte. Algunos de los números de palíndromo son 365563, 48984, 12321, 171, 88, 90009, 343 y algunas de las cuerdas de palíndromo son MADAM, MALAYALAM, LOL, DAD, MOM, C ++ y ++ C, etc. Veamos la lógica y la implementación del palíndromo en las siguientes secciones. En este tema, vamos a aprender sobre Palindrome en Java.

La lógica detrás de Palindrome en Java

Para verificar si un número es un palíndromo, se puede usar el siguiente algoritmo.

  • Tome una cadena de entrada o un número que debe verificarse si es un palíndromo o no.

Por ejemplo, tomemos el número 353 como entrada.

  • Tome el número de entrada y cópielo en una variable temporal

353-> temp

  • Invierta usando for, while o cualquier método de su elección.

Reversednumber: rev=353

  • Compare el número de entrada y el número invertido.

Si son iguales, entonces se dice que el número es un número de palíndromo.

De lo contrario, el número no es un número palíndromo.

es decir

If(inputnum==rev)
( then palindrome )
Else not palindrome

¿Cómo probar Palindrome usando varios métodos?

Existen varios métodos para verificar si el número de entrada dado es un palíndromo o no.

  1. En bucle
  2. Mientras bucle
  3. Método de biblioteca (para cadenas)

Echemos un vistazo a cada uno de ellos en detalle.

1. Programa para verificar el número de palíndromo usando for loop

//Java program to check whether a String is a Palindrome or not using For Loop
import java.util.*;
public class PalindromeNumberExample (
//main method
public static void main(String() args) (
int r=0 ; //reversed Integer
int rem, num; //remainder and original number
Scanner s = new Scanner(System.in);
System.out.print("Enter number that has to be checked:");
num = s.nextInt();
//Store the number in a temporary variable
int temp = num;
//loop to find the reverse of a number
for( ;num != 0; num /= 10 )
(
rem = num % 10; // find the modulus of the number when divided by 10
r = r * 10 + rem;
)
//check whether the original and reversed numbers are equal
if (temp == r)
(
System.out.println(temp + " is input number");
System.out.println(r + " is the reversed number");
System.out.println("Since they are equal " + temp + " is a palindrome number");
)
else
(
System.out.println(temp + " is input number");
System.out.println(r + " is the reversed number");
System.out.println("Since they are not equal " + temp + " is not a palindrome number");
)
)
)

Salida de muestra 1:

Aquí, como 353 es igual cuando se invierte, se considera como un palíndromo.

Salida de muestra 2:

Aquí, dado que 234 no es el mismo cuando se invierte, no se considera un palíndromo.

2. Programa para verificar el número de palíndromo usando el bucle While

//Java program to check whether a number is a Palindrome or not using While Loop
import java.util.*;
public class PalindromeNumberExample (
public static void main(String() args) (
int r=0, rem, num;
Scanner s = new Scanner(System.in);
System.out.print("Enter number that has to be checked:");
num = s.nextInt();
//Store the number in a temporary variable
int temp = num;
//loop to find the reverse of a number
while( num != 0 )
(
rem= num % 10;
r= r * 10 + rem;
num=num/10;
)
//check whether the original and reversed numbers are equal
if (temp == r)
(
System.out.println(temp + " is input number");
System.out.println(r + " is the reversed number");
System.out.println("Since they are equal " + temp + " is a palindrome number");
)
else
(
System.out.println(temp + " is input number");
System.out.println(r + " is the reversed number");
System.out.println("Since they are not equal " + temp + " is not a palindrome number");
)
)
)

Salida de muestra 1:

Salida de muestra 2:

3. Programa para verificar el número de palíndromo usando el método de la biblioteca (para cadenas)

//Java program to check whether a String is a Palindrome or not using Library method
import java.util.*;
public class PalindromeNumberExample (
//Function to check whether the string is palindrome or not
public static void PalindromeCheck(String str)
(
// reverse the input String
String rev = new StringBuffer(str).reverse().toString();
// checks whether the string is palindrome or not
if (str.equals(rev))
(
System.out.println("input string is :" + str);
System.out.println("Reversed string is :" + rev);
System.out.println("Since the input and reversed string are equal, "+ str +" is a palindrome");
)
else
(
System.out.println("input string is :" + str);
System.out.println("Reversed string is :" + rev);
System.out.println("Since the input and reversed string are not equal, "+ str +" is not a palindrome");
)
)
public static void main (String() args)
(
PalindromeCheck("MALAYALAM");
)
)

Salida de muestra:

Aquí, la cadena de entrada se pasa en el propio programa.

Para verificar si una cadena es un palíndromo, también se usa el siguiente programa.

//Java program to check whether a String is a Palindrome or not
import java.util.*;
public class PalindromeNumberExample (
public static void main(String args())
(
String st, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string that has to be checked:");
st = sc.nextLine();
int len = st.length(); //length of the string
for ( int i = len- 1; i >= 0; i-- )
rev = rev + st.charAt(i);
if (st.equals(rev))
(
System.out.println("input string is :" + st);
System.out.println("Reversed string is :" + rev);
System.out.println("Since the input and reversed string are equal, "+ st +" is a palindrome");
)
else
(
System.out.println("input string is :" + st);
System.out.println("Reversed string is :" + rev);
System.out.println("Since the input and reversed string are not equal, "+ st +" is not a palindrome");
)
)
)

Salida de muestra:

Conclusión

Se dice que un número es palíndromo si permanece igual incluso cuando se invierte. Un palíndromo se puede verificar en cadenas también. Algunos de los números y cadenas de palíndromo son MOM, MALAYALAM, DAD, LOL, 232, 1331, etc. En este documento, se cubren varios aspectos de Palindrome, tales como algoritmos, métodos, implementación, etc.

Artículos recomendados

Esta es una guía de Palindrome en Java. Aquí discutimos cómo probar Palindrome usando varios métodos con la salida de muestra. También puede echar un vistazo a los siguientes artículos para obtener más información:

  1. Raíz cuadrada en Java
  2. Número inverso en Java
  3. StringBuffer en Java
  4. CardLayout en Java
  5. Descripción general de Palindrome en C #
  6. Invertir en JavaScript
  7. Herramientas de implementación de Java
  8. Palindrome en C ++
  9. Raíz cuadrada en PHP
  10. Métodos de trabajo y Top 3 Enum en C #