我试图为Palindromes编写一个程序,但我的输出并不像预期的那样

时间:2014-09-29 13:48:30

标签: java palindrome

这是我的剧本

public class palindrome {

    public static void main(String[] args) {
        int rev = 0;

        Scanner r = new Scanner(System.in);

        System.out.println("enter any value");

        int n = r.nextInt();

        while (n != 0) {
            rev = rev * 10 + n % 10;
            n = n / 10;
        }

        System.out.println(rev);

        if (n == rev) {
            System.out.println("number is palindrome");
        } else {
            System.out.println("not palindrome");    
    }
}

2 个答案:

答案 0 :(得分:0)

在您的解决方案中,n始终为0.

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

http://java67.blogspot.co.il/2012/09/palindrome-java-program-to-check-number.html

答案 1 :(得分:0)

您应该将n的副本复制到另一个变量

 public static void main(String[] args) {
    int rev = 0;

    Scanner r = new Scanner(System.in);

    System.out.println("enter any value");

    int n = r.nextInt();
    int original = n;

    while (n != 0) {
        rev = rev * 10 + n % 10;
        n = n / 10;
    }

    System.out.println(rev);

    if (original == rev) {
        System.out.println("number is palindrome");
    } else {
        System.out.println("not palindrome");    
}