我正在尝试制作lychrel数字程序。但我做不到。标准是,列出10000以下的Lychrel数,有限的Lychrer数检查迭代。我被设定为30。但是我还没有得到答案。如果检查完成了30次迭代,则应列出数字。我没有得到解决方案。帮帮我。
public class LychrelNumber {
static final int MAX_NUMBER = 10000;
static final int MAX_ITERATION = 30;
int iterationCount = 0;
void listTheLychrelNymber() throws Exception {
long i = 0;
long temp;
for (int j = 0; j < MAX_NUMBER; j++) {
iterationCount = 0;
temp = j;
for (i = 0; i < MAX_ITERATION; i++) {
long first = temp;
long second = reverseTheNumber(temp);
long third = first + second;
long fourth = reverseTheNumber(third);
if (third == fourth) {
break;
} else {
temp = third;
if (i == MAX_ITERATION) {
System.out.println("Lychrel Numbers are :" + j);
}
}
}
}
}
long reverseTheNumber(long n) {
long reverse = 0;
while (n != 0) {
reverse = reverse * 10;
reverse = reverse + n % 10;
n = n / 10;
}
return reverse;
}
public static void main(String[] args) {
try {
LychrelNumber lychrelNumber = new LychrelNumber();
lychrelNumber.listTheLychrelNymber();
} catch (Exception e) {
}
}
}
它构建成功。但是我没有得到输出。
看看你的i循环(我把代码缩短了一点)
for (i = 0; i < MAX_ITERATION; i++) {
if (i == MAX_ITERATION) {
System.out.println("Lychrel Numbers are :" + j);
}
}
如您所见,当i达到MAX_ITERATION时,您将停止循环,但仅在i==MAX_ITERION的情况下在循环中打印Lychrel数(当然这永远不会发生)。
我得到了解决方案。
if (i == (MAX_ITERATION-1)) {
System.out.println("Lychrel Numbers are:" + j);
}
这是我在条件检查中犯的错误。。