我一直在用头撞墙,试图找出为什么会返回“错误答案”。如果有任何反馈,我将不胜感激。
编辑:我重新发布了代码,这个版本最终通过允许数字对之间存在多个空格来修复“运行时错误”。现在它说“错误答案”,但据我所知,我逐字复制了给定的算法,所以我不知所措。
谢谢。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
Main mine = new Main();
mine.begin();
}
public void begin(){
BufferedReader sys = new BufferedReader(new InputStreamReader(System.in));
String[] pair;
try{
while((pair=sys.readLine().split(" +")).length==2){
System.out.println(pair[0]+ " " +pair[1] + " " + getMax(Integer.parseInt(pair[0]),Integer.parseInt(pair[1])));
}
}catch(IOException ex){
return;
}
}
private String getMax(int a, int b){
int maxcount,thiscount, num, n;
for(maxcount = -1, num =Math.min(a, b); num <= Math.max(a, b); num++ ){
for(n = num, thiscount = 1; n!=1; thiscount++){
if(n%2==0)n=n/2;
else n = 3*n +1;
}
if(thiscount>maxcount) maxcount = thiscount;
}
return String.valueOf(maxcount);
}
}
最佳答案
while(num<4){
...
输入总是限制为 4 行吗?
关于java - (又一个)UVa 3n+1 帮助问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3848659/