如何检查一个数字是否是回文?

时间:2016-04-01 04:19:49

标签: java palindrome

我为课堂作业写了一段代码。但是我觉得它很长!有更优化的方法吗?

String text = input.readLine();
int num = (text.length())/2;
double letter = (double)(text.length())/2;
String s1 = text.substring(0,num);
int u1 = Integer.parseInt(s1);      

if (letter%1==0) {           
    StringBuffer s2 = new StringBuffer(text.substring(num));
    s2 = s2.reverse();
    String t2 = s2.toString();
    int u2 = Integer.parseInt(t2);
    if (u1==u2) {
        System.out.println("Palindrome");
    } else {
        System.out.println("FAIL");
    }
} else {
    StringBuffer s2 = new StringBuffer(text.substring(num+1));
    s2= s2.reverse();
    String t2 = s2.toString();
    int u2 = Integer.parseInt(t2);
    if (u1==u2) {
        System.out.println("Palindrom");
    }else {
        System.out.println("FAIL");
    }
}

2 个答案:

答案 0 :(得分:1)

您无需将字符串转换回数字即可进行比较。您可以使用字符串的equals()方法来检查它们是否相等。检查一下(通过必要的更改,这将适用于任何字符串,而不仅仅是数字)。

int num = 12300321;
String numString = String.valueOf(num);
String reverseNumString = new StringBuilder(numString).reverse().toString();

if(numString.equals(reverseNumString)) {
    System.out.println(num + " is a Palindrome!");
}
else {
    System.out.println(num + " is not a Palindrome!");
}

输出:

12300321 is a Palindrome!

替代方法(仅使用数字操作;仅适用于整数)

int num = 12300321;
int numCopy = num;
int reverseNumInt = 0;

while(numCopy != 0) {
    reverseNumInt = reverseNumInt * 10 + numCopy % 10;
    numCopy /= 10;
}
if(reverseNumInt == num) {
    System.out.println(num + " is a Palindrome!");
}
else {
    System.out.println(num + " is not a Palindrome!");
}

答案 1 :(得分:0)

您的代码有效,但逐位处理数字更简单,更易读:

public static boolean isPalindromic(String num) {
    for(int i = 0, len = num.length() ; i < len/2 ; i++) {
        if(num.charAt(i) != num.charAt(num.charAt(len-i-1))) return false;
    }

    return true;
}