> Java > java지도 시간 > 본문

자바의 회문

王林
풀어 주다: 2024-08-30 16:26:05
원래의
496명이 탐색했습니다.

문자열이나 숫자를 뒤집어도 그대로 유지되는 경우를 회문이라고 합니다. 예를 들어 'MADAM'은 뒤집어도 'MADAM'으로 표기되므로 회문 문자열입니다. 하지만 'LUCKY'의 경우 이 문자열을 역으로 바꾸면 'YKCUL'이 되므로 회문이 아닙니다. 회문 번호 중 일부는 365563, 48984, 12321, 171, 88, 90009, 343이고 회문 문자열 중 일부는 MADAM, MALAYALAM, LOL, DAD, MOM, C++&++C 등입니다. 다음 섹션에서 회문의 논리와 구현을 살펴보겠습니다. 이번 주제에서는 Java의 Palindrome에 대해 알아보겠습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java Palindrome의 논리

숫자가 회문인지 확인하려면 다음 알고리즘을 사용할 수 있습니다.

  • 회문인지 아닌지 확인해야 할 문자열이나 숫자를 입력받아보세요.

예를 들어 숫자 353을 입력한다고 가정해 보겠습니다.

  • 입력 숫자를 가져와 임시 변수에 복사합니다

353-> temp

  • for, while 또는 원하는 방법을 사용하여 반전하세요.

Reversednumber: rev=353

  • 입력된 숫자와 반전된 숫자를 비교해보세요.

같으면 그 숫자를 회문수라고 합니다.

그렇지 않으면 회문번호가 아닙니다.

즉,

If(inputnum==rev)
{ then palindrome }
Else not palindrome
로그인 후 복사

다양한 방법으로 Palindrome을 테스트하는 방법은 무엇입니까?

주어진 입력 숫자가 회문인지 여부를 확인하는 방법에는 여러 가지가 있습니다.

  • For 루프
  • While 루프
  • 라이브러리 방법(문자열용)

각각 자세히 살펴보겠습니다.

1. 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");
}
}
}
로그인 후 복사

출력 1:

자바의 회문

여기서 353은 거꾸로 해도 똑같으므로 회문으로 간주합니다.

출력 2:

자바의 회문

여기서 234는 뒤집어도 그대로 남아 있으므로 회문으로 간주되지 않습니다.

2. 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");
}
}
}
로그인 후 복사

출력 1:

자바의 회문

출력 2:

자바의 회문

3. 라이브러리 메소드를 사용하여 회문 번호를 확인하는 프로그램(문자열의 경우)

코드:

//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");
}
}
로그인 후 복사

출력:

자바의 회문

여기서 입력 문자열은 프로그램 자체에 전달됩니다.

문자열이 회문인지 확인하려면 다음 프로그램도 사용됩니다.

코드:

//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");
}
}
}
로그인 후 복사

출력:

자바의 회문

결론

뒤집어도 그대로 유지되는 숫자를 회문이라고 합니다. 회문은 문자열로도 확인할 수 있습니다. 회문 숫자와 문자열 중 일부는 MOM, MALAYALAM, DAD, LOL, 232, 1331 등입니다. 이 문서에서는 알고리즘, 메서드, 구현 등과 같은 회문의 여러 측면을 다룹니다.

위 내용은 자바의 회문의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!