【POJ 1426 --- Find The Multiple】取余+DFS
题目来源:点击进入【POJ 1426 — Find The Multiple】
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
解题思路
根据题意,我们需要找到一个只由1和0组成的十进制数,最高位固定为1.并且该数还是输入数的倍数。
那么我们可以DFS搜索所有情况,每次遍历只有两种情况:x10或者x10+1;
直到找到符合要求的数。因为n的范围是200,所以2的18次方以内就足以,直接用long long.
AC代码:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
#define endl '\n'
typedef long long ll;
ll ans,n;
void dfs(ll x,int cnt)
{
if(ans) return;
if(x%n==0)
{
ans=x;
return;
}
if(cnt==18) return;
dfs(x*10,cnt+1);
dfs(x*10+1,cnt+1);
}
int main()
{
SIS;
while(cin >> n, n)
{
ans=0;
dfs(1,0);
cout << ans << endl;
}
return 0;
}