【Java语言程序设计(基础篇)第10版 练习题答案】Practice_6_3

时间:2023-02-24 00:04:08

by Pierpont and Piggy
(回文整数)使用下面的方法头编写两个方法:

  //Return the reversal of an integer, i.e.,reverse(456) return 654
  public static int reverse(int number)

  //Return true if number is a palindrome
  public static boolean isPalindrome(int number)

使用 reverse 方法实现 isPalindrome。如果一个数字的方向倒置数和它的顺向数一样,这个数就称为回文数。编写一个测试程序,提示用户输入一个整数值,然后报告这个整数是否是回文。

import java.util.Scanner;

public class Practice_6_3 {

    public static void main(String args[]) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter an integer: ");
        int n = input.nextInt();

        if(isPalindrome(n) == true)
            System.out.println("The number is a palindrome");
        else
            System.out.println("The number is not a palindrome");

    }

    public static int reverse(int number) {

        int temp = 0;

        for(; number != 0; ) {
            temp *= 10;
            temp += number % 10;
            number /= 10;
        }

        return temp;

    }

    public static boolean isPalindrome(int number) {
        if(number == reverse(number))
            return true;
        else
            return false;
    }
}

输出示例:

Enter an integer: 456
The number is not a palindrome

or

Enter an integer: 456654
The number is a palindrome