palindrom回文数(java)

1.设计题目

Statement of the Problem

We say that a number is a palindrom if it is the sane when read from left to right or from right to left. For example, the number 75457 is a palindrom.

Of course, the property depends on the basis in which is number is represented. The number 17 is not a palindrom in base 10, but its representation in base 2 (10001) is a palindrom.

The objective of this problem is to verify if a set of given numbers are palindroms in any basis from 2 to 16.

Input Format

Several integer numbers comprise the input. Each number 0 < n < 50000 is given in decimal basis in a separate line. The input ends with a zero.

Output Format

Your program must print the message Number i is palindrom in basis where I is the given number, followed by the basis where the representation of the number is a palindrom. If the number is not a palindrom in any basis between 2 and 16, your program must print the message Number i is not palindrom.

题目翻译:

问题陈述:如果一个数字从左到右或从右到左读的时候是正常的,我们就说它是回文。例如,数字75457是回文。当然,属性取决于数字的表示基础。数字17不是以10为底的回文,但以2为底的数字(10001)是回文。这个问题的目的是验证一组给定的数字是否是以从2到16为底的回文。

输入格式:几个整数组成了输入。每一个0<n<50000的数字在单独的一行中以十进制为基础给出。输入以零结束。

输出格式:您的程序必须输出Number i is palindrom,其中i是给定的数字,后跟表示数字为回文的数字。如果数字在2到16之间不是回文,程序必须输出Number i is not palindrom。

2.问题描述

输入0<n<50000的整数(输入0结束),判断是否是以2到16为底的回文数,按照题目要求给出相应的启示信息。

3.问题分析

先将输入的n转换为2到16进制的数存储在一个一维数组中,经过循环判断是否为回文数,然后在利用变量输出语句,以及输出那些进制下可以是回文数

4.代码实现

import java.util.Scanner;
public class Design_03palindrom {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        long n , num;     //n代表输入的数字,
        while((n = input.nextLong()) != 0){     //当输入的n为0时停止循环;
            boolean match = true;
            String str = "";
            for(int basis = 2 ; basis <= 16 ; basis ++){
                num = Conversion(n,basis);
                str = String.valueOf(num);
                String strr = new StringBuffer(str).reverse().toString();
                if(str.equals(strr)){
                    match = false;
                    System.out.println("Number " + n + " is palindrom in basis " + basis);
                }
            }
            if(match) System.out.println("Number " + n + " is not a palindrom");
        }
        input.close();
    }
    public static long Conversion(long n , long m){
        long temp = 0 , r = 0 , t = 0;
        while(n != 0) {
            r = n % m;
            n /= m;
            temp += (long) (r * Math.pow(10, t));
            t ++;
        }
        return temp;
    }
}

5.运行结果

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值