365. Water and Jug Problem

莫名奇妙找了个奇怪的规律。

每次用大的减小的,然后差值和小的再减,减减减减减减到差值=0为止。(较小的数 和 差值 相等为止,这么说更确切)

然后看能不能整除就行了。

有些特殊情况。

看答案是用GCD做的,2行就写出来了,但是不是很理解。

Ax + By = z,A B为正负 int,就是有接。。神奇。

放个自己写的垃圾代码。

public class Solution {
    public boolean canMeasureWater(int x, int y, int z) 
    {
        
        if(z>x+y) return false;
        if(z == 0) return true;
        if(x == y) return (z==x) || (z == 2*x);
        if(x == 0 || y == 0) return (z == x) || (z == y);
        if(z%x == 0 || z % y == 0) return true;
        
        
        int large = Math.max(x,y);
        int small = Math.min(x,y);
        int diff = large - small;
        
        while(diff != small)
        {
            large = Math.max(diff,small);
            small = Math.min(diff,small);
            diff = large - small;
        }
        
        
        return z%diff == 0;
    }
}

GCD的两行纯复制粘贴,不是很明白:

public boolean gcd(int a, int b)
    {
        return b == 0? a:gcd(b,a%b);
    }
    public boolean canMeasureWater(int x, int y, int z) 
    {
        return ( x + y > z && z % gcd(x,y) == 0) || x + y == z;
    }
posted @ 2016-09-15 05:52  哇呀呀..生气啦~  阅读(104)  评论(0编辑  收藏  举报