如何解决乌龟赛车问题

Abd*_*bri 1 java

有一个问题叫:乌龟赛车.

问题是:

名为A和B的两只乌龟必须参加比赛.A的平均速度为每小时720英尺.年轻的B知道她跑得比A快,而且还没有完成她的卷心菜.

当她开始时,她终于可以看到A有70英尺的领先但B的速度是每小时850英尺.B要花多长时间才能抓到A?

更一般地说:给定两个速度v1(A的速度,整数> 0)和v2(B的速度,整数> 0)和一个导程g(整数> 0),B需要多长时间才能捕获A?

结果将是一个数组[小时,分钟,秒],这是小时,分钟和秒所需的时间(向下舍入到最接近的秒)或某些语言的字符串.

如果V1> V2 =然后返回nil,什么都没有,NULL,无或{-1,-1,-1}为C++,C,围棋,稔,[对于科特林]或 "-1 -1 -1".

示例:(结果的形式取决于语言)

种族(720,850,70)=> [0,32,18]或"0 32 18"

种族(80,91,37)=> [3,21,49]或"3 21 49"

我试着像这样解决它:

  public static int[] race(int v1, int v2, int g) {

            int v3 = v2 - v1;
            double time = (double )g / (double)v3;
            int result[] = new int[3];

            if (v2 > v1) {
                if (time > 1) {
                    while (time > 10) {
                        time /= 10;
                    }
                    result[0] = (int) time;
                    result[1] = (int) ((time - result[0]) * 60);
                    result[2] = (int) ((((time - result[0]) * 60) - result[1]) * 60);
                    System.out.print(result[0] + " " + result[1] + " " + result[2]);
                } else {
                    result[0] = 0;
                    result[1] = (int) (time * 60);
                    result[2] = (int) (((time * 60) - result[1]) * 60);
                    System.out.print(result[0] + " " + result[1] + " " + result[2]);
                }
            }
            else {
                return null;
            }

            return result;
        }
Run Code Online (Sandbox Code Playgroud)

但它一直在测试用例上失败,你能帮帮我吗?

Sha*_*wat 8

检查以下代码:

public class Tortoise {
    public static int[] race(int v1, int v2, int g) {
        if (v1 >= v2)
            return null;
        int seconds = (g * 3600) / (v2 - v1);
        return new int[]{seconds / 3600, (seconds % 3600) / 60, seconds % 60};
    }

    public static void main(String[] args) {
        Tortoise.race(720, 850, 70);
    }
}
Run Code Online (Sandbox Code Playgroud)