Java solution based on modulus property


  • 0
    Q

    Let's find situation where there is no solution.

    1. x is multiple of y
    2. y is multiple of x.
    3. x is 0 or y is 0
    4. x+y>z



      This does not mathematically prove that there is no other conditions, but this is enough to pass all the tests, and when I picked x and y that are not multiples of each other I was able to find the solution.
    public boolean canMeasureWater(int x, int y, int z) {
        if (z==x+y || z==x || z==y || z==0)
            return true;
        if (x==0 || y==0 || x%y ==0 || y%x ==0 || z>x+y)
            return false;
        return true;
    }

  • 2
    4

    x = 4, y = 6, z = 1? should be false right? but returns true in your program i think? correct me if i'm wrong


  • 0
    Q

    Modified to pass 4,6,1 case

    public boolean canMeasureWater(int x, int y, int z) {
        if (z==x+y || z==x || z==y || z==0)
            return true;
        if (x==0 || y==0 || z>x+y || z%GCF(x,y)!=0)
            return false;
        return true;
    }
    private int GCF(int x, int y) {
        return y==0?x:GCF(y, x%y);
    }

  • 0
    Q

    Thanks, using greatest common factor takes care of this case.


  • 0

    Thanks, I have added your test case.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.