[kuangbin takes you to fly] E - Find The Multiple [Search]

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
1111111111111111111 

The meaning of the title: Given a n (1<=n<=200), find a multiple m of it, m must be composed of 0 and 1 The

idea: Use search to enumerate 0, 1 bitwise, once you find a match If the condition is m, stop searching for the

specific implementation: at the beginning, considering that the number of results will be relatively large, I used a string to enumerate m, and then converted it to a long long type, the result overflowed, and later I checked it online. After a while, I found that there is no need to use string,
there is a simpler search process: dfs(num*10,k+1) dfs(num*10+1,k+1), num represents the m that is currently being tried, such as trying now 10, 10% 3! =0, then there are two cases for the next bit: 100 and 101,
so it is num*10 and num*10+1, k indicates how many bits have been enumerated currently, why add this flag? Because long long can represent about 1e19, the search should be terminated when k==19, otherwise it will overflow.
Another question is how to make it stop searching when it finds a matching m? You can set a flag variable flag, the initial value is 0, and set to 1 when found

AC code:
#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;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324805270&siteId=291194637