You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs.
If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.
Operations allowed:
- Fill any of the jugs completely with water.
- Empty any of the jugs.
- Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.
Example 1: (From the famous "Die Hard" example)
Input: x = 3, y = 5, z = 4
Output: True
Example 2:
Input: x = 2, y = 6, z = 5
Output: False
这道题在考察大家的观察能力。
举个例子。如果我的两个壶都是偶数,请问能量出奇数的结果吗?
所以,通过观察发现,我们能产生的最少量的水,其实是两个壶的最大公倍数。然后其余能够测量的水就以最大公倍数递增,直到装满两个壶。
注意输入的壶的容量有0的情况。
class Solution {
private:
int gcd(int a, int b) {
if (a < b) swap(a, b);
while (b > 1) {
if (a % b == 0) return b;
int tmp = a;
a = b;
b = tmp % a;
}
return 1;
}
public:
bool canMeasureWater(int x, int y, int z) {
if(x==0 || y == 0) return x==z || y==z;
int gcd = this->gcd(x, y);
if (z % gcd == 0 && z <= x + y) return true;
else return 0;
}
};