首页 > USACO题解 > USACO Dual Palindromes

USACO Dual Palindromes

USACO Dual Palindromes又是一个进制转换和回文数判断相关的题目,跟上一个题目“USACO Palindromic Squares”类似,可以重用一下上一个题目的代码:

/*
	ID:stackex1
	LANG:C
	PROG:dualpal
*/
#include <stdio.h>
#include <string.h>

void num2str(int num, char *s, int base)
{
	char map[] = {"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
	char dst[64];
	int i = 0, n;
	while(num)
	{
		dst[i++] = map[num % base];
		num /= base;
	}
	dst[i] = '\0';
	n = i;
	for(i = n - 1; i >= 0; --i)
	{
		s[n -1 - i] = dst[i];
	}
	s[n] = '\0';
}

int isPal(char *s)
{
	int i, n;
	n = strlen(s);
	for(i = 0; i <= n/2; ++i)
	{
		if(s[i] != s[n - i - 1])break;
	}
	if(i <= n/2)return 0;
	return 1;
}

int main(int argc, char **argv)
{
	FILE *fin = fopen("dualpal.in", "r");
	FILE *fout = fopen("dualpal.out", "w");
	
	int n, s, num, base, cnt;
	char str[32];
	fscanf(fin, "%d %d", &n, &s);
	num = 0;
	while(num < n)
	{
		cnt = 0;
		base = 2;
		++s;
		while(cnt < 2 && base <= 10)
		{
			num2str(s, str, base);
			if(isPal(str)) ++cnt;
			++base;
		}
		if(cnt >= 2)
		{
			++num;
			fprintf(fout, "%d\n", s);
		}
	}
	
	fclose(fin);
	fclose(fout);

	return 0;
}

觉得文章还不错?点击此处对作者进行打赏!


本文地址: 程序人生 >> USACO Dual Palindromes
作者:代码疯子(Wins0n) 本站内容如无声明均属原创,转载请保留作者信息与原文链接,谢谢!


更多



  1. 本文目前尚无任何评论.