POJ1426 Find The Multiple
题目链接:https://vjudge.net/problem/POJ-1426
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
题目大意:对于一个数n,给出n的倍数m,要求m是由01组成的十进制数。
解题思路:运用DFS进行搜索,从1开始进行,随后在数的后面加1或者0,直到找到m为止。
Cpp Code
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#include<cstdio>
#define ll long long
using namespace std;
ll flag = 0,x,n;
void DFS(int step,ll x){
if(step>19||flag==1){//long long二点最大值是19位,搜索19次找不到答案则退出
return;
}
if(x%n==0){
flag = 1;
printf("%lld\n", x);
return;
}
DFS(step + 1, x * 10);
DFS(step + 1, x * 10+1);
}
int main(){
while((scanf("%lld",&n)==1)&&n){
flag = 0;
DFS(1,1);
}
return 0;
}
Java Code
import java.util.Scanner;
public class Main {
static long n;
static boolean tag=false;
public static void DFS(int step,long x) {
if(step>19||tag==true) {//long的最大值是19位数,搜索19次找不到答案则退出
return;
}
if(x%n==0) {
tag=true;
System.out.println(x);
return;
}
DFS(step+1,x*10);
DFS(step+1,x*10+1);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(true) {
n=sc.nextLong();
if(n==(long)0) {
break;
}
tag=false;
DFS(1,1);
}
sc.close();
}
}

浙公网安备 33010602011771号