[kuangbin带你飞]E - Find The Multiple [搜索]

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.

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

题意:给定一个n(1<=n<=200),求一个它的倍数m,m必须是由0和1构成的

思路:用搜索,按位枚举0,1,一旦找到符合条件的m,就停止搜索

具体实现:在刚开始考虑到结果的数字会比较大,所以我用了字符串枚举m,然后把它转为long long类型,结果出现了溢出,后来在网上查了一下发现不需要用string,
有一种更简单的搜索过程:dfs(num*10,k+1) dfs(num*10+1,k+1),num表示当前正在尝试的m,比如现在试了10,10%3!=0,那么下一位有两种情况:100和101,
所以是num*10和num*10+1,k表示当前已经枚举了多少位,为什么要加这个标志呢?因为long long大约能表示到1e19,所以,在k==19时要终止搜索,否则会溢出。
还有一个问题就是如何让它找到一个符合条件的m就停止搜索呢?可以设一个标志变量flag,初始值为0,找到后设为1

AC代码:
#include <iostream>
#include <cstring>
/* 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.  */
//数据范围:1<=n<=200
using namespace std;
long long n;
bool flag = 0;
 void bfs(long long num,int k){
     if(flag) return;    
    if(num%n==0){
        flag=1;
        cout<<num<<endl;
        return;
    }
    if(k==19) return;
    bfs(num*10,k+1);
    bfs(num*10+1,k+1);
}
int main(int argc, char** argv) {
    while(scanf("%lld",&n)!=EOF&&n!=0){
        flag = 0;
        bfs(1,1);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/jiaqi666/p/8934408.html