Leetcode

Water and Jug Problem

  • Time:O(1)
  • Space:O(1)

C++

class Solution {
 public:
  bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
    return targetCapacity == 0 ||
           jug1Capacity + jug2Capacity >= targetCapacity &&
               targetCapacity % __gcd(jug1Capacity, jug2Capacity) == 0;
  }
};

JAVA

class Solution {
  public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
    return targetCapacity == 0 || jug1Capacity + jug2Capacity >= targetCapacity &&
                                      targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}

Python

class Solution:
  def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:
    return targetCapacity == 0 or \
        jug1Capacity + jug2Capacity >= targetCapacity and \
        targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0