(OJ)Java基础-回文数

回文数

Problem Description

1.实验目的
    掌握if-else if多分支语句 

2.实验内容 
  用户输入一个1-99999之间的整数,程序判断这个数是几位数,并判断是否回文数,回文数将指该数含有的数字逆序排列后得到的数和原数相同,例如12121、3223等。

3.实验要求 
   请将下列代码补充完整

  import java.util.*;
  public class Main
 {  
    public static void main(String args[])
    {
       int d5,d4,d3,d2,d1;
        Scanner cin=new Scanner(System.in);
        int number = cin.nextInt();
        if(number<=99999&&number>=1) //判断number在1至99999之间的条件
            {
               d5=number/10000;   //计算number的最高位(万位)d5
               d4=number%10000/1000;   //计算number的千位d4

        // 你的代码

Input Description

1-99999之间的整数

Output Description

有下列三种输出情况,例如:
  (1) 3223 is 4-digit number, is a palindrome number
  (2) 34561 is 5-digit number, isn't a palindrome number
  (3) 567890 is not in 1-99999

Sample Input

3445

Sample Output

3445 is 4-digit number, isn't a palindrome number

Hint

提示:获取命令行输入内容 
Scanner cin=new Scanner(System.in);
int number = cin.nextInt();

解题代码

			/**
             * 这题是一个代码补全题
             * 根据题意可知,应该只是判断4位数和五位数是否为回文数
             * 对于五位数 个位 = 万位 并且 十位 = 千位 即为回文数
             * 对于四位数 个位 = 千位 并且 十位 = 百位 即为回文数
             */
            // 计算number的百位d3
            d3 = number % 1000 / 100;
            // 计算number的十位d2
            d2 = number % 100 / 10;
            // 计算number的个位d1
            d1 = number % 10;
            // 如果万位d5为0 则代表这个数是四位数
            if (d5 == 0){
    
    
                // 如果个位 = 千位 并且 十位 = 百位 即为回文数 输出结果
                if(d1 == d4 && d2 == d3){
    
    
                    System.out.println(number + " is 4-digit number, is a palindrome number");
                // 否则 不为回文数 输出结果
                } else{
    
    
                    System.out.println(number + " is 4-digit number, isn't a palindrome number");
                }
            // 如果是五位数
            }else {
    
    
                // 如果个位 = 万位 并且 十位 = 千位 即为回文数 输出相关信息
                if(d1 == d5 && d2 == d4){
    
    
                    System.out.println(number + " is 5-digit number, is a palindrome number");
                // 不是回文数 输出相关信息
                } else{
    
    
                    System.out.println(number + " is 5-digit number, isn't a palindrome number");
                }
            }
        // 不是1-99999之间的数 输出相关信息
        }else {
    
    
            System.out.println(number + " is not in 1-99999");
        }
		// 关闭Scanner 输入流
		cin.close();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40856560/article/details/112523793