C语言课程设计——palindrom

设计题目——palindrom

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. Eachnumber 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.

2 . 题目含义

首先,题目中举了一个75457的回文数 作为例子。第二段又举了一个 17 在二进制的时候 10001 也是回文数

最后一段 提出要求:判断一个数i(0<i<50000) 在2-16 进制下,是否为回文数

输出结果也有要求:若是回文数 输出“ Number i is palindrom in basis where I is the given number” 若不是输出“Number i is not palindrom”

3 . 解决办法

通过阅读题目,解决问题有两点:1. 如何判断回文数 2. 如何将这个数转化其他进制下的数。

第一个问题 :判断回文数 。先将这个数保存在字符数组中 s[j] 与 s[i-j-1] 判断二者是否相等即可 如果有一个数字不相等,即可返回 0 。若全部都相等 返回1。

第二个问题:进制转换关系是:n%m 所得到的余数 然后 n/=m 继续求余数,直到n=0. 求到的每一个余数排列起来就是m进制下的数字,保存到字符数组中。设置一个 i用于计数。方便知道s[]数组中有几个数。

将上述两个问题包装到一个函数中 check ( n , m) n是要判断的数字 m是要换算的进制。

在主函数中,写一个循环 for (m=2;m<=16;m++)每一个进制都调用一次check函数。把check函数的返回值作为printf输出的判断条件。

如果所有进制下都不是回文数,才输出“Number i is not palindrom”

4 . 流程图

在这里插入图片描述

5 . 代码实现
#include <stdio.h>
int check(int n, int m){
	char table[17] = "0123456789ABCDEF";
	char s[20];
	int i = 0, j;
	while(n){
		s[i] =table[n%m];
		n/=m;
		i++;
	}
	for(j=0;j<i-j-1;j++){
		if(s[j]!=s[i-j-1])
		return 0;
	}
	return 1;
	}
int main(){
	int n,i,c;
	while(scanf("%d",&n)==1){
		c = 0;
		for(i=2;i<=16;i++)
		if(check(n,i)){
			c = 1;
			printf("Number %d is palindrom in basis %d.\n",n,i);
		}
		if(!c)
		printf("Number %d is not palindrom.\n",n);
		}
}
6 . 运行结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值