我想实现两种方法来检查数字是否是回文

时间:2016-10-09 16:04:00

标签: java palindrome

如上所述,我有两种方法,

public static int reverse(int number)

public static boolean isPalindrome(int number)

我应该安排他们检查一个号码是否是回文。我试图应用提示(一个数字是回文,如果(它的逆转==本身)),但它没有帮助。

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {

        System.out.println("This program checks whether a number is palindrome or not. Enter a number: ");
        Scanner input = new Scanner(System.in);
        int inputNumber = input.nextInt();

        // if inputNumber is palindrome 

        System.out.println("The number is palindrome.");

        // else 

        System.out.println("The number is not a palindrome.");
    }


        public static int reverse(int number)

        // reverse number


        public static boolean isPalindrome(int number)

        // check if the number is palindrome     
    }
}

4 个答案:

答案 0 :(得分:2)

为了反转一个数字,你应该将它除以10并将余数加到一个新的反转数字乘以10。

例如,这将是恢复123的步骤:

  1. 反转= 0,目标= 123
  2. 反转= 0 * 10 + 123%10 = 0 + 3 = 3,目标= 123/10 = 12
  3. 反转= 3 * 10 + 12%10 = 30 + 2 = 32,目标= 12/10 = 1
  4. 反转= 32 * 10 + 1%10 = 320 + 1 = 321,目标= 1/10 = 0
  5. 以下是Java中该算法的实现:

    public static int reverse(int number) {
        int reversed = 0;
        while (number > 0) {
            reversed *= 10;
            reversed += number % 10;
            number /= 10;
        }
        return reversed;
    }
    
    public static boolean isPalindrome(int number) {
        return number == reverse(number);
    }
    

答案 1 :(得分:0)

尝试使用此方法进行反向。

Step0  : temp = 0 number  = 4554
Step 1 : temp = 4 number = 455
Step 2 : temp = 4*10 +  5 = 45 and number = 45
Step 3 : temp = 45*10 + 5 = 455 and number  = 4
Step 4 : temp = 455*10 + 4 = 4554 and number  = 0


    if (inputNumber == reverse(inputNumber)) {
        System.out.println("The number is palindrome.");
    }else{
        System.out.println("The number is not a palindrome.");
    }

public static int reverse(int number) {
    int temp = 0;
    while (number > 0) {
        temp = temp * 10 + number % 10;
        number = number / 10;
    }
    return temp;
}

答案 2 :(得分:0)

"Hello - Adele (Cover)" -> "Hello - Adele "
"Flo Rida - Wild Ones ft. Sia [Official Video]" -> "Flo Rida - Wild Ones ft. Sia"
"Hello - Adele (Cover) [Video]"

这是解决问题的方法。但这并不包括我可以进入" 011"该计划将说" 11"是一个回文。我怎么能解决这个问题?

答案 3 :(得分:0)

以下算法将起作用

1. Loop until the input number become 0.

    1.1 remainder = number % 10;
    1.2 reverse = reverse * 10 + remainder;
    1.3 number = number / 10;

2. Return reverse when the loop breaks. That means number became 0.

Check full implementation here