My straight forward soln, no Math (C#)


  • 0
    L

    I have never thought to solve this problem by math. (Maybe my math is weak). But, the logical of problem is not difficult. First, return all impossible cases, then make the container smaller and smaller.
    My solution is not better, but easy to understand for who does not familiar with Math.

    public bool CanMeasureWater(int x, int y, int z) {
        if (z == x || z == y || z == 0)
            return true;
                
        if (x <= 0 || y <= 0)
            return false;
    
        if (z == x + y || z == Math.Abs(x - y))
            return true;
    
        if (z > x + y)
            return false;
    
        if (x == 1 || y == 1)
            return true;
    
        if ((y != 0 && z % y == 0 ) || (x != 0 && z % x == 0))
            return true;
    
        if (x > y) {
            return CanMeasureWater(x % y, y, z % y);
        } else {
            return CanMeasureWater(x, y % x, z % x);
        }
    }
    
    

Log in to reply
 

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