例题7-1 除法

【题目描述】

输入正整数n,按从小到大的顺序输出所有形如abcde / fghij = n的表达式,其中a~j恰好为数字0~9的一个排列(可以有前导0),2≤n≤79

input:

62

output:

79546 / 01293 = 62

94736 / 01528 = 62

【分析】

暴力也有暴力的技巧,是否需要枚举0-9的所有排列?没这个必要!只需要枚举fghij就可以算出abcde,然后判断是否所有数字均不相等即可。(对于除法,简化为利用乘法反求结果 )

其中涉及到的sprintf()函数:摘自 https://blog.csdn.net/xiaoyao_chicheng/article/details/53224175

原型:int sprintf( char *buffer, const char *format, [argument] … );
buffer:char型指针,指向将要写入的字符串的缓冲区。
format:格式化字符串。
[argument]...:可选参数,可以是任何类型的数据。

%nd 表示输出的整型宽度至少为n位,右对齐,%5d即宽度至少为5位,位数大于5则输出实际位数
%0nd 表示输出的整型宽度至少为n位,不足n位用0填充
【代码】

#include<iostream>
#include<string>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1000 + 10;
int main()
{
	int n;
	cin >> n;
	for (int i = 1234;;i++)
	{
		int t = i * n;
		char str[maxn];
		sprintf(str, "%05d%05d", t, i);	//将两个五位数部分组合导入字符串
		int len = strlen(str), flag = 1;
		if (len > 10) break;
		sort(str, str + len);
		for (int j = 0;j < 10;j++)
			if (str[j] != j + '0') flag = 0;
		if (flag) {
			printf("%05d / %05d = %d\n", t, i, n);//类比于sprintf的%0nd
		}
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cprimesplus/article/details/84349247
7-1
今日推荐