java实现回文_Java语言实现palindrome(回文)

Java语言实现palindrome(回文)

设计题目

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 Format11

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就是回文。

当然,该属性取决于表示is number的基。数字17不是以10为基底的回文,但它以2为基底(10001)表示是回文

这个问题的目的是验证-组给定的数字 否是从2到1 6的任意组回文

输入格式.

输入由几个整数组成。每个数字0

输出格式

您的程序必须打印消息编号i是回文的基础中是给定的数字,然后是数字的表示是回文的基础。如果数字不是在2到1 6之间的任何基础上的回文,您的程序必须打印消息编号i不是回文。

Java:

import java.util.Scanner;

public class Palindrome {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

long n;

while((n = sc.nextLong()) != 0){ // 输入以零结束

long num;

boolean book = true;

String str = null;

for(int i = 2;i <= 16;i++) { // (2-16) 进制

num = decimalToMRadix(n, i); // 将 n 转化成 i 进制

str = String.valueOf(num); // 变成字符串形式

// 以 str 作为构造StringBuffer对象的参数,再反转后转化成字符串

String strreverse = new StringBuffer(str).reverse().toString();

if(str.equals(strreverse)) { // 判断是否是回文

book = false; // 是回文数字

System.out.println(n + " 是以 " + i + " 为基底的回文数字");

}

}

if(book)

System.out.println(n + " 不是回文数字");

}

sc.close();

}

public static long decimalToMRadix(long n, long m) { // 将 n 十进制转化成 m(2-16) 进制

long mradix = 0, r = 0, t = 0;

while(n != 0) {

r = n % m;

n /= m; // 改变 n 值

mradix += (long) (r * Math.pow(10, t));

t++;

}

return mradix;

}

}

/*Code Running Results

17

17 是以 2 为基底的回文数字

17 是以 4 为基底的回文数字

17 是以 16 为基底的回文数字

59

59 是以 4 为基底的回文数字

59 是以 15 为基底的回文数字

523

523 是以 13 为基底的回文数字

598

598 是以 4 为基底的回文数字

598 是以 15 为基底的回文数字

0

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值