搜索--Find The Multiple

Find The Multiple
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 35088 Accepted: 14644 Special Judge
Description

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
题意:就是给定一个数,找到一个只由0,1组成的数并且可以整除给定的数
思路:直接一个搜索就可以,操作就有两个,一个是10,另个是10+1,这道题深搜广搜都是可以的,但还有一种很有意思的解法。

code:


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
long long mod[1000000];
int main(){
    int n;
    while(~scanf("%d",&n)&&n){
        int i;
        for(i = 1;; i++){//这里要从一开始,为什么看下面
            mod[i] = mod[i/2]*10+i%2;//这时关键语句,实际上和上一个代码的深搜是一个道理,只不过用循环代替了,很巧妙,我们来分析一下
            //因为每次只有两个操作,所以第i个数,应该由第i/2个数*10或者*10+1得到,因为每次都要乘十,所以每次都乘,只不过就是加一或者不加的问题
            //这里就巧妙用到下标奇偶性质,奇数模2为1,就相当与加一,而偶数相当于不加,所以下标从1开始是方便的,你可能问开始的两个加一或不加会不会出现零,因为题目要求不能出现
            //零,不会,因为第一个是1,第二个发现虽然不加1但是2/2=1了所以第二个元素还是1,所以从下标1开始很神奇!
            if(mod[i]%n==0){
                printf("%lld\n",mod[i]);
                break;
            }
        }
    }
    return 0;
}


发布了66 篇原创文章 · 获赞 7 · 访问量 2036

猜你喜欢

转载自blog.csdn.net/dajiangyou123456/article/details/104032855
今日推荐