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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43516020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:57:54  来源:igfitidea点击:

How to check if a number is palindrome in Java?

java

提问by Leo Lee

I am new in Java and I need to complete this program to check if an integer is palindrome. Please help.

我是 Java 新手,我需要完成这个程序来检查一个整数是否是回文。请帮忙。

public static void main(String args[]){

    System.out.println("Please enter an integer : ");
    int integer = new Scanner(System.in).nextInt();

    if(isPalindrome(integer)){
        System.out.println(integer + " is a palindrome");
    }else{
        System.out.println(integer + " is not a palindrome");
    }       

}

采纳答案by Sky

public static boolean isPalindrome(int integer) {
    int palindrome = integer;
    int reverse = 0;

    // Compute the reverse
    while (palindrome != 0) {
        int remainder = palindrome % 10;
        reverse = reverse * 10 + remainder;
        palindrome = palindrome / 10;
    }

    // The integer is palindrome if integer and reverse are equal
    return integer == reverse; // Improved by Peter Lawrey

}

Advanced solution: (Provided by Shadov)

高级解决方案:(Shadov 提供)

public static boolean isPalindrome(int integer) {
    String intStr = String.valueOf(integer); 
    return intStr.equals(new StringBuilder(intStr).reverse().toString());
}

Reference: http://www.java67.com/2012/09/palindrome-java-program-to-check-number.html#ixzz4emXfiD7V

参考:http: //www.java67.com/2012/09/palindrome-java-program-to-check-number.html#ixzz4emXfiD7V

Please do not just put up question without your work next time.

下次请不要在没有工作的情况下提出问题。

回答by Hello Kitty

public static boolean isPalindrome(int number) {
    int palindrome = number; // copied number into variable
    int reverse = 0;

    while (palindrome != 0) {
        int remainder = palindrome % 10;
        reverse = reverse * 10 + remainder;
        palindrome = palindrome / 10;
    }

    // if original and reverse of number is equal means
    // number is palindrome in Java
    if (number == reverse) {
        return true;
    }
    return false;
}

Source: http://www.java67.com/2012/09/palindrome-java-program-to-check-number.html#ixzz4emXfiD7V

来源:http: //www.java67.com/2012/09/palindrome-java-program-to-check-number.html#ixzz4emXfiD7V

But you need to clearly not put up homework questions here.

但是你需要明确不要在这里提出家庭作业问题。