《算法竞赛入门经典》 第五章 基础题目选解

本文主要探讨了《算法竞赛入门经典》第五章的内容,聚焦于字符串问题,包括WERTYU、TeX括号和周期串的解题思路。同时,深入讲解了高精度运算,涵盖小学生算术原理以及阶乘的精确计算方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

5.1 字符串

5.11 WERTYU

// 5.1.1 WERTYU

#include <stdio.h>
char *s = "1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./";
int main(void)
{
	int i, c;
	while((c = getchar()) != EOF)
	{
		for(i = 1; s[i] && s[i] != c; i++)
			;
		if(s[i])
			putchar(s[i-1]);
		else
			putchar(c);
	}
	return 0;
}


5.1.2 TeX括号

// 5.1.2 TeX括号

#include <stdio.h>
int main(void)
{
	int c, q = 1;
	while((c = getchar()) != EOF)
	{
		if(c == '"')
		{
			printf("%s", q ? "``" : "''");
			q = !q;
		}
		else
			printf("%c", c);
	}
	return 0;
}


5.1.3 周期串

// 5.1.3 周期串

#include <stdio.h>
#include <string.h>
int main(void)
{
	char word[100];
	scanf("%s", word);
	int len = strlen(word);
	for(int i = 1; i <= len; i++)
		if(len % i == 0)
		{
			int ok = 1;
			for(int j = 1; j < len; j++)
				if(word[j] != word[j%i])
				{
					ok = 0;
					break;
				}
			if(ok)
			{
				printf("%d\n", i);
				break;
			}
		}
}

 

5.2 高精度运算
5.2.1 小学生算术

// 5.2.1 小学生算术

#include <stdio.h>
int main(void)
{
	int a, b;
	while(scanf("%d%d", &a, &b) == 2)
	{
		if(!a && !b)
			return 0;
		int c = 0, ans = 0;
		for(int i = 9; i >= 0; i--)
		{
			c = (a%10 + b%10) > 9 ? 1 : 0;
			ans += c;
			a /= 10;
			b /= 10;
		}
		printf("%d\n", ans);
	}
	return 0;
}


5.2.2 阶乘的精确值

// 5.2.2 阶乘的精确值

#include <stdio.h>
#include <string.h>
#define MAXN 3000
int f[MAXN];
/*
const int maxn = 3000;
int f[maxn];

这样写会报错
.c|6|error: variably modified 'f' at file scope|
因为const在C中定义的时可读变量,maxn依旧是变量,不能用变量声明数组长度
*/
int main(void)
{
	int i, j, n;
	scanf("%d", &n);
	memset(f, 0, sizeof(f));
	f[0] = 1;
	for(i = 2; i <= n; i++)
	{	//乘以i
		int c = 0;
		for(j = 0; j < MAXN; j++)
		{
			int s = f[j] * i + c;
			f[j] = s % 10;
			c = s/10;
		}
	}
	for(j = MAXN-1; j >= 0; j--)
		if(f[j])
			break;
	for(i = j; i >= 0; i--)
		printf("%d", f[i]);
	printf("\n");
	return 0;
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值