Find The Multiple
Time Limit: 1000MS | Memory Limit: 10000K | |||
Total Submissions: 24137 | Accepted: 9997 | 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
1 2 3 4 |
2 6 19 0 |
Sample Output
1 2 3 |
10 100100100100100100 111111111111111111 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
题目大意: 给出一个数n,找出找出一个数要求是n的倍数,并且这个数的十进制只由1和0组成。 因为是special judge,所以不止一个答案的只要输出一个正确的答案就可以了。 解题思路: 虽然题目的分类是BFS广度优先搜索,但用DFS也可以解决。 反正由01组成的数字,对于前一个数来说,要么是t * 10,要么是t * 10 + 1,所以只要两个dfs就可。 我试了一下,判题最大只需要unsinged long int 即可AC,如果是用int 、long int这些就会WA。 记得设置最多递归19层,如果还没找到就直接return ; 代码非常简洁: #include <iostream> using namespace std; int flag; int n; void dfs(unsigned long int t,int k) { if (flag == 1) return ; if (t % n == 0) { cout << t << endl; flag = 1; return ; } if (k == 19) //到第19层还没找到那就回溯,别找了 return ; dfs(t * 10, k + 1); dfs(t * 10 + 1, k + 1); } int main() { while (cin >> n && n != 0) { flag = 0; dfs(1, 0); } } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼