java - (又一个)UVa 3n+1 帮助问题

标签 java

我一直在用头撞墙,试图找出为什么会返回“错误答案”。如果有任何反馈,我将不胜感激。

编辑:我重新发布了代码,这个版本最终通过允许数字对之间存在多个空格来修复“运行时错误”。现在它说“错误答案”,但据我所知,我逐字复制了给定的算法,所以我不知所措。

谢谢。

The Problem

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/

相关文章:

java - JPA/Hibernate无法理解持久顺序

java - 使用 Calendar 和 SimpleDateFormat 将时间转换为 "HH:mm:ss"会增加 1 小时

java - 带有空对象的 JPA 查询

java - 使用 Spring 的 REST Api 实现

java - Sonarqube 安全报告 : OWASP Top 10

java - 在关闭连接时禁用 oracle 自动提交

java - GamesClient 未连接。错误 : "Call connect() and wait for onConnected() to be called."

java - Spring : Injection of autowired dependencies failed

java - 从 ArrayList<CustomObject> 中查找项目索引的更好方法

java - 谁将像在 C++ 中一样在 Java 中扮演 Friend 函数的角色?