water-and-jug-problem

以下这个解法也是参考了一些讨论:

https://leetcode.com/discuss/110235/c-solution-using-euclidean-algorithm

还有这个解释原理的,没有看懂:https://leetcode.com/discuss/110525/a-little-explanation-on-gcd-method

 

class Solution {
    int gcd(int a, int b) {
        // below suppose a <= b
        // and if b < a, then b%a == b
        return a==0?b:gcd(b%a, a);
    }
public:
    bool canMeasureWater(int x, int y, int z) {
        // notice, operator priority: % > == > && > ||
        // so below is equivalent to
        // (z == 0) || ((z <= (x+y)) && ((z % gcd(x,y)) == 0))
        return z == 0 || z <= (x+y) && z % gcd(x, y) == 0;
    }
};
31 / 31 test cases passed.
Status: 

Accepted

Runtime: 0 ms
posted @ 2016-06-27 14:45  blcblc  阅读(294)  评论(0编辑  收藏  举报