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: **
Input: x = 3, y = 5, z = 4
Output: True
Example 2:
Input: x = 2, y = 6, z = 5
Output: False
這道題實際上是道數學智力題,求解的關鍵就是判斷z能否整除x與y的最大公約數。當然,這道題有些隱藏約束,就是z<=x+y
以及z可以為0,當然多過幾遍測試用例基本上就能察覺了。上代碼:
/**
* @param {number} x
* @param {number} y
* @param {number} z
* @return {boolean}
*/
var canMeasureWater = function (x, y, z) {
const findDivisor = function (a, b) {
while (b) {
let c = a % b;
a = b;
b = c;
}
return a;
};
const divisor = findDivisor(x, y);
if (z > x + y) {
return false;
}
else if (z === x || z === y || z === 0) {
return true;
}
return (z % divisor === 0);
};
需要一些優化的地方可能就是找最大公約數了,這里我選用了輾轉相除的方法。當然也有輾轉相減和暴力循環的方式。具體算法可以自行百度一下。