[我已经为[Advant of Code 2015 Day 4] [1]编写了代码,并为自己(貌似)开始工作感到自豪。我已经将其设置为在我的笔记本电脑上的BlueJ中运行,到目前为止已经花费了一个多小时才能运行。我只是想知道我是否意外地将其置于一个无限循环中?它是运行数字,因为如果每次运行for循环时都在变量末尾打印,它将给出一个字符串(很好)。我只是想知道它是否会找到以五个零开头的答案,并且会继续颤抖。
提前感谢。
非常感谢,
本
编辑:感谢C.B.注意到charAt()错误。
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
// Java program to calculate MD5 hash value
public class Main {
public static String getMD5(String input) {
try {
// Static getInstance method is called with hashing MD5
MessageDigest md = MessageDigest.getInstance("MD5");
// digest() method is called to calculate message digest
// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static String toHex(String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes()));
}
// Driver code
public static void main(String args[]) throws NoSuchAlgorithmException {
boolean finish = false;
int ans = 0;
for (int i = 0; finish == false; i++) {
String input = "yzbqklnj"+i;
String hash = getMD5(input);
String end = toHex(getMD5(input));
if (end.charAt(0)=='0' && end.charAt(1)=='0' && end.charAt(2)=='0' && end.charAt(3)=='0' && end.charAt(4)=='0'){
System.out.println("Your answer is "+i);
finish = true;
}
}
}
}
[1]: https://adventofcode.com/2015/day/4
不应该end.charAt(0)==0
是end.charAt(0)=='0'
?
由于您正在检查end.charAt(0)==0
而不是end.charAt(0)=='0'
,依此类推,因此以下if
条件的计算结果为false
,这意味着finish
将永远不会设置为true
,从而导致for
循环运行无限。
if (end.charAt(0)==0 && end.charAt(1)==0 && end.charAt(2)==0 && end.charAt(3)==0 && end.charAt(4)==0)