1.将字符串反转后逐一比较
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String str1 = "54415";
int aaa = 5445;
String str2 = String.valueOf(aaa);
System.out.println(isPalindrome(str1));
System.out.println(isPalindrome(str2));
}
public static boolean isPalindrome(String str) {
StringBuilder s1 = new StringBuilder(str);
s1.reverse();
int n = str.length();
int count = 0;
for (int i = 0; i < n; i++) {
if (str.charAt(i) == s1.charAt(i)) {
count++;
}
}
if (count == n) {
return true;
} else {
return false;
}
}
}
输出:
false
true
2.将字符串反转后创建新字符串直接比较
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String str1 = "54145";
int aaa = 544015;
String str2 = String.valueOf(aaa);
System.out.println(isPalindrome(str1));
System.out.println(isPalindrome(str2));
}
public static boolean isPalindrome(String str) {
StringBuilder s1 = new StringBuilder(str);
s1.reverse();
String s2 = new String(s1);
if (str.equals(s2)) {
return true;
} else {
return false;
}
}
}
输出:
true
false
3.使用截取字符串的方式比较
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String str1 = "541045";
int aaa = 544445;
String str2 = String.valueOf(aaa);
System.out.println(isPalindrome(str1));
System.out.println(isPalindrome(str2));
}
public static boolean isPalindrome(String str) {
int count = 0;
for (int i = 0; i < str.length() / 2; i++) {
if ((str.substring(i, i + 1)).equals(str.substring(str.length() - 1 - i, str.length() - i))) {
count++;
}
}
if (count == str.length() / 2) {
return true;
} else {
return false;
}
}
}
输出:
false
true
4.纯数字判断回文的方法
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
int a1 = 5445;
int a2 = 54415;
System.out.println(isPalindrome(a1));
System.out.println(isPalindrome(a2));
}
public static boolean isPalindrome(int n) {
int temp = n;
int m = 0;
while (temp != 0) {
m = m * 10 + temp % 10;
temp /= 10;
}
if (m == n) {
return true;
} else {
return false;
}
}
}
输出:
true
false



