Given a positive integer n, write a program to find out anonzero multiple m of n whose decimal representation contains only the digits 0and 1. You may assume that n is not greater than 200 and there is acorresponding m containing no more than 100 decimal digits.
Input
The input file may contain multiple test cases. Each linecontains a value of n (1 <= n <= 200). A line containing a zeroterminates the input.
Output
For each value of n in the input print a line containingthe corresponding value of m. The decimal representation of m must not containmore 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
题意:
输入一个数n(n<=200);找个100位以内的由0和1组成的数,若找到多个,只输出其中一个就行.
思路:可以用dfs 写,也可以用bfs写,但要注意了,这道题找的数用longlong能存下.
起始位一定是 1 是吧,以后面跟0,或者1,假设另sum=1,它的下一个数是sum*10或sum*10+1,所以就有两条路可以走,代码如下,dfs ,bfs 的都有,还有我当时
不知道有longlong能存下时写的内存超限的代码
我写的代码适合初学者看
这是用dfs写的
#include<stdio.h>
int f;
long long n;
void dfs(long long x,int step) //题意上说是一百位,但longlong就能存下 step 为位数
{
if(f||step>18) // 大于18位就return,我觉着一定是事先知道,能被200之内的正整
return ; // 数由0 1组成的数,在18位之内一定能找到一个
if(x%n==0)
{
f=1; //若找到就返回主函数
printf("%lld\n",x) ;
return ;
}
dfs(x*10,step+1); // 这个有两种情况 这个是后面加0
if(f) return ;
dfs(x*10+1,step+1);//这个是后面加1
if(f) return ;
}
int main()
{
int i,j,k,t;
while(~scanf("%lld",&n)&&n)
{
f=0;
dfs(1,0);
}
return 0;
}
用 bfs 写的:
#include<stdio.h>
int n,f;
struct st
{
long long sum;
}stu[1111000];
void bfs()
{
stu[0].sum=1;
int star=0,end=1;
while(star<end)
{
for(int i=1;i<=2;i++)
{
long long x;
if(i==1)
x=stu[star].sum*10;
else
x=stu[star].sum*10+1;
if(x>=9223372036854775807)
continue;
stu[end].sum=x;
if(x%n==0)
{
printf("%lld\n",x);
return ;
}
end++;
}
star++;
}
}
int main()
{
int i,j,k,t;
while(~scanf("%d",&n)&&n)
{
f=0;
if(1%n==0)
{
printf("1\n");
continue;
}
bfs();
}
return 0;
}
#include<stdio.h>
int n,f;
struct st
{
char s[300]; //用存0 和 1 组成的数
int sum; // 这个是上一个由0 1组成的数除以n 剩下的余数;
int l; //这个是多少位
}stu[111000];
void bfs()
{
stu[0].s[0]='1';
stu[0].sum=1;
stu[0].l=0;
int star=0,end=1;
while(star<end)
{
int i,j;
for(i=1;i<=2;i++)
{
for(j=0;j<=stu[star].l;j++)
stu[end].s[j]=stu[star].s[j];
int sum=stu[star].sum;
if(i==1)
{
stu[end].s[j]='0';
sum=sum*10;
}
else if(i==2)
{
stu[end].s[j]='1';
sum=sum*10+1;
}
int sum1=sum%n;
stu[end].sum=sum1;
stu[end].l=j;
if(sum1==0)
{
f=1;
printf("%s\n",stu[end].s);
return ;
}
if(j>100) return ;
end++;
}
star++;
}
}
int main()
{
int i,j,k,t;
while(~scanf("%d",&n)&&n)
{
f=0;
if(1%n==0)
{
printf("1\n");
continue;
}
bfs();
}
return 0;
}
错误原因:
我不知道用long long 能存下,还有就是小编能力有限,应该还有好的方法,望博友给提些建议;