简体   繁体   English

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

[英]How to check if a number is a palindrome?

I wrote a piece of code for a class homework.我为课堂作业写了一段代码。 However I thought it was quite long!不过我觉得很长! Is there a more optimized way to do this?有没有更优化的方法来做到这一点?

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");
    }
}

You don't need to convert the string back to number in order to compare them.您不需要将字符串转换回数字来比较它们。 You can use string's equals() method to check if they are equal.您可以使用字符串的equals()方法来检查它们是否相等。 Check this out (with necessary changes this will work for any string though, not just numbers).检查一下(进行必要的更改,这将适用于任何字符串,而不仅仅是数字)。

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!");
}

Output:输出:

12300321 is a Palindrome!

Alternate method (using only number manipulation; will work for integers only)替代方法(仅使用数字操作;仅适用于整数)

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!");
}

Your code works, but handling the numbers digit by digit is simpler and more readable:您的代码有效,但逐位处理数字更简单且更具可读性:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM