边工作边刷题:70天一遍leetcode: day 41-2
Water and Jug Problem
要点:利用了Bézout’s theorem:mx+n*y对于任意m,n都是gcd(x,y)的整倍数。所以z是gcd整倍数并且z<=x+y
- gcd(a,b):a一定<b做辗转相除。结束条件是a=0,返回b(和1没关系)。而gcd==0只可能a=b=0
class Solution(object):
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
def gcd(a, b): # assume a<b
if a==0: return b # error 1: return b not return 0
return gcd(b%a, a)
if x>y: x,y=y,x
gval = gcd(x,y)
#print gval
if gval==0:
return z==0
return z%gval==0 and z<=x+y