Find The Multiple(dfs+思维)

Find The Multiple(dfs + 思维)

题目描述

Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.

大意:
给定一个正整数n,求一个只含有 0 和 1 的 n 的倍数,数据保证 n <= 200,输出要求不超过100位数。

Input
The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.

Output
For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.

Sample Input

2
6
19
0

Sample Output

10
100100100100100100
111111111111111111

思路

最开始想用高精做:开一个 105 位的数组(a[105]),从个位(即a[1])开始,一位一位地选择数字,但是代码写出来之后发现,一些数位可取 1 也可取 0(如 11 * 1 末尾为 1,11 * 0末尾则为 0),因此若使用 if 语句容易造成找不出正确答案。

后来(请教大佬+网上找答案)仔细思考过后,通过打表(数学方法证明暂时没想到),我们容易得出,答案不会超过 19 位数,因此不需要 105 位的数组,使用 unsigned long long 即可满足题目要求。

因此此题便成为一道经典dfs题目:定义函数 dfs(unsigned long long d, int total),total 代表共选择了几位数,d 代表此时的数字。每次递归执行 dfs 时只需分两种情况:
1)下一位数字选择 0 ,即 dfs(d * 10, total + 1)
2)下一位数字选择 1,即 dfs(d * 10 + 1, total + 1)

void dfs(unsigned long long d, int total)
{
	if (flag) return;
	if (d % n == 0)
	{
		flag = 1;
		printf("%llu\n", d);
		return;
	}
	if (total >= 19) return;
	dfs(d * 10, total + 1);
	dfs(d * 10 + 1, total + 1);
}

Note:

1)当 total == 19 时应当退出循环(防止超过 ull 的数据范围)
2)定义一个全局变量 flag,在找到答案后结束 dfs 的运行,防止输出多组解。或是用一个变量将解储存起来,结束 dfs 后输出,但此方法耗时稍长
3)ull 型数据输出时格式为 %llu

AC代码

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<algorithm>
using namespace std;

int n;
bool flag;

unsigned long long da;

void dfs(unsigned long long d, int total)
{
	if (flag) return;
	if (d % n == 0)
	{
		flag = 1;
		printf("%llu\n", d);
		return;
	}
	if (total >= 19) return;
	dfs(d * 10, total + 1);
	dfs(d * 10 + 1, total + 1);
}


int main()
{
	while (~scanf("%d", &n) && n != 0)
	{
		flag = 0;
		dfs(1, 0);
	}
}

总结

此题坑点主要在于题目中给出“ 100 位数字”这一误导信息,让人难以看出是一道 dfs 问题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值