import java.util.Scanner;
public class HuiWenTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.next();
if (input.matches("\\d+")) {
ArrayCharArray(input);
StringBufferReverse(input);
isPalindrome(input);
checkHWS(input);
getHuiWen(input);
getHuiWenShu(input);
getHuiWen2(input);
}
}
private static void getHuiWen2(String input) {
boolean b = true;
for (int i = 0; i < input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - i - 1)) {
b = false;
break;
}
}
System.out.println("方法7==" + input + (b ? "是" : "不是") + "回文数");
}
private static void getHuiWenShu(String input) {
int count = 0;
for (int i = 0; i < input.length() / 2; i++) {
if ((input.substring(i, i + 1))
.equals(input.substring(input.length() - 1 - i, input.length() - i))) {
count++;
}
}
if (count == input.length() / 2) {
System.out.println("方法6===是回文字符串");
} else {
System.out.println("方法6===不是回文字符串");
}
}
private static void getHuiWen(String input) {
StringBuffer sb = new StringBuffer(input);
sb.reverse();
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == sb.charAt(i)) {
count++;
}
}
if (count == input.length()) {
System.out.println("方法5==此字符串是一个回文字符串");
} else {
System.out.println("方法5==此字符串不是一个回文字符串");
}
}
public static boolean checkHWS(String inputString) {
int input = Integer.parseInt(inputString);
int reverse = 0, temp = input;
while (temp > 0) {
reverse = reverse * 10 + temp % 10;
temp = temp / 10;
}
if (input == reverse) {
System.out.println("方法4==" + input + "是回文数!");
return true;
}
System.out.println("方法4==" + input + "不是回文数!");
return false;
}
private static boolean isPalindrome(String input) {
int begin = 0, end = input.length() - 1;
char[] chars = input.toCharArray();
while (begin < end) {
if (chars[begin] == chars[end]) {
begin++;
end--;
} else {
System.out.println("方法3 ==" + input + "不是回文数!!!");
return false;
}
}
System.out.println("方法3 ==" + input + "是回文数!!!");
return true;
}
private static boolean ArrayCharArray(String input) {
char[] nums = input.toCharArray();
String output = "";
for (int i = nums.length; i > 0; i--) {
output += nums[i - 1];
}
System.out.println("方法1 ==input==" + input);
System.out.println("方法1 ==output==" + output);
if (output.equals(input)) {
System.out.println("方法1 ==" + input + "是回文数!!!");
return true;
}
System.out.println("方法1 ==" + input + "不是回文数!!!");
return false;
}
private static boolean StringBufferReverse(String input) {
StringBuffer sbInput = new StringBuffer(input);
StringBuffer sbReverse = sbInput.reverse();
String output = sbReverse.toString();
System.out.println("方法2 ==input==" + input);
System.out.println("方法2 ==output==" + output);
if (input.equals(output)) {
System.out.println("方法2 ==" + input + "是回文数!!!");
return true;
}
System.out.println("方法2 ==" + input + "不是回文数!!!");
return false;
}
}
参考:
java判断回文字符串的几种方法