这道题我是用深搜+Java BigInteger做的。已经很慢了,但是还是能通过题目的测试。我猜原因可能是控制了深度:if (num.bitLength() > 100)。其实题目要求是10进制下小于100位,这里是二进制下,因而限制更紧了(与题目不符),但是还是过了。
看了discuss,这道题是可以用long long的,因为答案中最大的就19位,这样不用BigInteger,运算会快很多。
thestoryofsnow | 1426 | Accepted | 5592K | 2125MS | Java |
import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class Poj1426 {
final static int MAXN = 200 + 1;
final static BigInteger ZERO = BigInteger.ZERO;
final static BigInteger ONE = BigInteger.ONE;
final static BigInteger TEN = BigInteger.TEN;
public static void main(String args[])
{
Scanner cin = new Scanner(System.in);
Integer n;
while (cin.hasNext())
{
n = cin.nextInt();
if (n == 0)
{
break;
}
BigInteger N = BigInteger.valueOf(n);
System.out.println(multiple(ONE, N));
}
}
public static BigInteger multiple(BigInteger num, BigInteger N)
{
// System.out.println("N = " + N + "," + num + "[" + num.bitLength() + "]");
if (num.bitLength() > 100)
{
return null;
}
if (num.mod(N).equals(ZERO))
{
return num;
}
BigInteger left = num.multiply(TEN), right = left.add(ONE);
BigInteger goleft = multiple(left, N);
if (goleft != null)
{
return goleft;
}
return multiple(right, N);
}
}