Introdução ao Palindrome em Java

Uma String ou um número é considerado um palíndromo se permanecer o mesmo, mesmo depois de revertido. Por exemplo, 'MADAM' é uma sequência de palíndromo, pois está escrita 'MADAM' mesmo que seja revertida. Mas no caso de 'LUCKY', essa sequência não é palíndromo, pois é 'YKCUL' quando é revertida. Alguns dos números do palíndromo são 365563, 48984, 12321, 171, 88, 90009, 343 e algumas das seqüências do palíndromo são MADAM, MALAYALAM, LOL, DAD, MOM, C ++ e ++ C, etc. Vamos ver a lógica e a implementação do palíndromo nas seções a seguir. Neste tópico, vamos aprender sobre o Palindrome em Java.

A lógica por trás do Palindrome em Java

Para verificar se um número é um palíndromo, o seguinte algoritmo pode ser usado.

  • Pegue uma sequência ou número de entrada que precise ser verificado se é um palíndromo ou não.

Por exemplo, vamos pegar o número 353 como entrada.

  • Pegue o número de entrada e copie-o em uma variável temp

353-> temp

  • Inverta usando, enquanto ou qualquer método de sua escolha.

Reversednumber: rev=353

  • Compare o número de entrada e o número reverso.

Se eles são iguais, então o número é considerado um número palíndromo.

Senão, o número não é um número palíndromo.

ie

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

Como testar o Palindrome usando vários métodos?

Existem vários métodos para verificar se o número de entrada fornecido é um palíndromo ou não.

  1. For Loop
  2. Enquanto Loop
  3. Método de biblioteca (para strings)

Vamos analisar cada um deles em detalhes.

1. Programa para verificar o número do palíndromo usando o loop for

//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");
)
)
)

Saída de amostra 1:

Aqui, como 353 é o mesmo quando invertido, é considerado um palíndromo.

Saída de amostra 2:

Aqui, como 234 permanece o mesmo quando invertido, não é considerado um palíndromo.

2. Programe para verificar o número do palíndromo usando o loop 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");
)
)
)

Saída de amostra 1:

Saída de amostra 2:

3. Programa para verificar o número do palíndromo usando o Método da Biblioteca (para strings)

//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");
)
)

Saída de amostra:

Aqui, a sequência de entrada é passada no próprio programa.

Para verificar se uma sequência é um palíndromo, o programa a seguir também é usado.

//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");
)
)
)

Saída de amostra:

Conclusão

Diz-se que um número é palíndromo se permanecer o mesmo, mesmo quando for revertido. Um palíndromo também pode ser verificado em seqüências de caracteres. Alguns dos números e seqüências de caracteres do palíndromo são MOM, MALAYALAM, DAD, LOL, 232, 1331 etc. Neste documento, vários aspectos do Palindrome são abordados, como algoritmo, métodos, implementação etc.

Artigos recomendados

Este é um guia para o Palindrome em Java. Aqui discutimos como testar o Palindrome usando vários métodos com a saída de amostra. Você também pode consultar os seguintes artigos para saber mais -

  1. Raiz quadrada em Java
  2. Número reverso em Java
  3. StringBuffer em Java
  4. CardLayout em Java
  5. Visão geral do Palindrome em C #
  6. Inverter em JavaScript
  7. Ferramentas de implantação Java
  8. Palíndromo em C ++
  9. Raiz quadrada em PHP
  10. Trabalho e os 3 principais métodos enum em C #