码迷,mamicode.com
首页 > 其他好文 > 详细

water-and-jug-problem

时间:2016-06-27 15:38:27      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:

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

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

water-and-jug-problem

标签:

原文地址:http://www.cnblogs.com/charlesblc/p/5620143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!