Title Description:
You are given the jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it's possible to measure exactly zlitres using these-jugs.
Operations allowed:
- Fill any of the jugs completely.
- Empty any of the jugs.
- Pour water from one jug to another till the other jug are completely full or the first jug itself is empty.
Problem Solving Analysis:
This is my undergraduate time algorithm class to a classic problem. Two bottles may be the amount of water is a multiple of the maximum number of two bottle capacity conventions. So just determine if z can be divisible by x, Y greatest common divisor.
Specific code:
1 Public classSolution {2 Public Static BooleanCanmeasurewater (intXintYintz) {3 intn=Math.max (x, y);4 intm=math.min (x, y);5x=N;6y=m;7 if(z>x)8 return false;9 if(z==x| | z==y)Ten return true; Onen=Fun (x, y); A returnZ%n==0; - } - //find the greatest common divisor of x, y the Public Static intFunintXinty) { - if(x%y==0) - returny; - while(x%y!=0){ + intM=math.max (xy, y); - intN=math.min (xy, y); +x=m; Ay=N; at } - returny; - } -}
"Leetcode" 365. Water and Jug problem