Java 检查回文数
回文一词源自希腊词palin dromo,意思是再次倒退。当数字、字符串或短语反转时仍然保持不变,即正反读取相同,被称为回文。例如,数字回文包括525,2002和12121。而单词回文是’ABA’,’BABAB’和’RADAR’。要在Java中检查回文,我们可以使用while循环和if-else语句块,判断给定的数字或字符串及其倒转是否相同。
Java程序检查回文
在本节中,我们将编写不同的Java程序来检查给定输入是否为回文。在此之前,让我们通过一个示例来讨论问题陈述的情况-。
实例
输入1
121
输出
121 is a Palindrome
输入2
34431
输出
34431 is not a Palindrome
输入3
"ABABA"
输出
ABABA is a Palindrome
现在,让我们来看一下Java程序,检查回文。
示例1
在这个示例中,我们将从用户那里输入一个数字,并检查该数字是否是一个回文数。我们还会使用while循环和if-else条件块来帮助判断。
import java.util.*;
public class Example1 {
public static void main(String[] args) {
// creating an instance of Scanner class
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number to check palindrome: ");
// to take input from user
int num = sc.nextInt();
// copying the original input
int copy = num;
// variable to store the result
int revVal = 0;
// loop to check palindrome
while(copy != 0) {
int rem = copy % 10; // extracting remainder
copy /= 10; // dividing and storing the number
revVal = revVal * 10 + rem; // reversing
}
// checking whether the reverse and original number is same or not
if(num == revVal) {
System.out.println(num + " is a Palindrome number");
} else {
System.out.println(num + " is not a Palindrome number");
}
}
}
输出1
Enter a number to check palindrome:
323
323 is a Palindrome number
输出2
Enter a number to check palindrome:
258
258 is not a Palindrome number
示例2
下面的示例说明了我们如何检查一个字符串是否是回文的。我们将使用StringBuffer类的内置方法reverse()来颠倒给定的字符串。然后,我们将这个颠倒的字符串传递给equals()方法,以检查原始字符串和颠倒后的字符串是否相同。如果两者相同,则字符串是回文的,否则不是。
public class Example2 {
public static void main (String[] args) {
String str = "ABABA";
System.out.println("The original String is: " + str);
// reversing the original string
String strRev = new StringBuffer(str).reverse().toString();
// checking whether the reverse is equal to the original string
if (str.equals(strRev)) {
System.out.println(str + " is a Palindrome!");
} else {
System.out.println(str + " is not a Palindrome!");
}
}
}
输出
The original String is: ABABA
ABABA is a Palindrome!
示例3
这是另一个Java程序,用于检查给定的数字是否是回文数。
public class Example3 {
public static void main(String[] args) {
int num = 52525;
System.out.println("The original number is: " + num);
// copying the original input
int copy = num;
// variable to store the result
int revVal = 0;
// loop to check palindrome
while(copy != 0) {
int rem = copy % 10; // extracting remainder
copy /= 10; // dividing and storing the number
revVal = revVal * 10 + rem; // reversing
}
// checking whether the reverse and original number is same or not
if(num == revVal) {
System.out.println(num + " is a Palindrome number");
} else {
System.out.println(num + " is not a Palindrome number");
}
}
}
输出
The original number is: 52525
52525 is a Palindrome number
结论
在这篇文章中,我们学习了Java中的回文。此外,我们还讨论了不同的Java程序,说明了如何检查给定输入是否为回文。实现这一目标最直接的方法是使用StringBuffer类的内置方法reverse()。