Codility - Frogjmp - 需要改进

时间:2015-02-17 11:06:12

标签: java

我试图从Codility为Frogjmp编写代码。 我试过这个解决方案和其他人一起,我不能100%得到。 (其他答案产生较低分数)

class Solution {
    public int solution(int X, int Y, int D) {
        // write your code in Java SE 8
        int diff = Y - X;
        int steps = 0;
        if( D != 0){
            if((diff % D) == 0)
                steps = diff %  D;
            else
                steps = diff / D + 1;
        }
        return steps;
    }
}

我不确定这里到底出了什么问题。

谢谢。

这是我第一次在这里寻求帮助,如果我在标题或其他方面犯了错误,请原谅我。

4 个答案:

答案 0 :(得分:1)

    if( D != 0){
        if((diff % D) == 0)
            steps = diff %  D; // this should be steps = diff / D;
                               // since you don't want to assign 0 to steps
        else
            steps = diff / D + 1;
    }

答案 1 :(得分:1)

对于这个frogJump代码,这是更优雅的解决方案。它表现出100%的鳕鱼。

    int distanceToJump = Y-X;
    //not a valid distance to jump
    if(distanceToJump <= 0){
        return 0;
    }else if(distanceToJump % D > 0){
        return (distanceToJump / D)+1;
    }else{
        return distanceToJump/D;
    }

答案 2 :(得分:1)

我的解决方案:

public int solution(int X, int Y, int D) {
    return (int) Math.ceil(((double) Y - X) / D);
}

https://codility.com/demo/results/trainingZHDKSS-96K/

答案 3 :(得分:0)

假设指出X≤Y,this solution显示100%的编码:

function solution(X, Y, D) {
    // write your code in JavaScript (Node.js 6.4.0)
    return Math.ceil((Y - X) / D);
}