回文数是颠倒后保持不变的数字,例如121、313、525等。
现在让我们看一个检查回文的例子-
public class Palindrome { public static void main(String[] args) { int a = 525, revVal = 0, remainder, val; val = a; System.out.println("Number to be checked = "+a); while( a != 0 ) { remainder = a % 10; revVal = revVal * 10 + remainder; a /= 10; } if (val == revVal) System.out.println("Palindrome!"); else System.out.println("不是回文!"); } }
输出结果
Number to be checked = 525 Palindrome!
现在让我们检查回文字符串,例如“ aba”,“ wow”等-
public class Demo { public static void main (String[] args) { String str = "ABA"; String strRev = new StringBuffer(str).reverse().toString(); if (str.equals(strRev)) System.out.println("Palindrome!"); else System.out.println("不是回文!"); } }
输出结果
Palindrome!