回文数(或回文数)是指一个像14641这样“对称”的数,即:将这个数的数字按相反的顺序重新排列后,所得到的数和原来的数一样。这里,“回文”是指像“妈妈爱我,我爱妈妈”这样的,正读反读都相同的单词或句子。
回文数在休闲数学领域备受关注。一个典型的问题就是,寻找那些具有某种特性,并且符合回文特征的数。例如:
- 回文素数:2, 3, 5, 7, 11, 101, 131, 151,…
- 回文完全平方数:0, 1, 4, 9, 121, 484, 676, 10201, 12321,…
public class PalindromeExample1 {
public static void main(String args[]) {
int r, sum = 0, temp;
int n = 454;// It is the number variable to be checked for palindrome
temp = n;
while (n > 0) {
r = n % 10; // getting remainder
sum = (sum * 10) + r;
n = n / 10;
}
if (temp == sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
点击查看结果
palindrome number
import java.util.Scanner;
public class PalindromeExample2 {
public static void main(String args[]) {
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
in.close();
}
}
参考资料