【发布时间】:2019-04-18 12:13:54
【问题描述】:
我必须找到第 100 位数字(不包括数字 3、4、7),但这需要很长时间,大约 9 秒才能找出如何提高性能。
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
public class FirstChallange {
private static int removedNumbers;
private static int numberQuantity;
private static int lastNumberFound;
private static int cont;
private static int pos3;
private static int pos4;
private static int pos7;
public static void main(String[] args)
{
long inicio = System.currentTimeMillis();
removedNumbers = 0;
numberQuantity = 10000000;
for (cont = 1; removedNumbers <= numberQuantity; cont++) {
String str = new String();
str = String.valueOf(cont);
pos3 = str.indexOf("3");
pos4 = str.indexOf("4");
pos7 = str.indexOf("7");
if((pos3 == -1) && (pos4 == -1) && (pos7 == -1)) {
removedNumbers++;
if(removedNumbers == numberQuantity){ // can not find numbers (3, 4, 7)
lastNumberFound = cont;
}
}
}
DecimalFormat dfmt = new DecimalFormat("0");
System.out.println(dfmt.format(lastNumberFound));
long fim = System.currentTimeMillis();
System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(fim - inicio)));
}
}
将数字转换为字符串并使用 indexOf 最佳模式删除它们?还是有什么比 indexOf 更好的,比如 RabinKarp?
预期结果:180999565 在 5/4 秒内
【问题讨论】:
-
如果您的代码有效并且需要优化,您应该将其发布到codereview.stackexchange.com
-
您应该以完全不同的方式思考问题。在每十年的自然数中,有 7 个是可以的:如果你必须说出第 20 个,应该是 29。你能算出 100 个自然数、1000 个、100 万个自然数的数字吗?第 40 个 OK 数字 not 等细节为 58(但 88)。一旦编程,2019 年的计算设备应该需要几毫秒,如果那样的话。
-
(Errm.我必须找到第千个数字 ↔
numberQuantity = 10000000?!)
标签: java algorithm performance numbers