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 z litres using these-jugs.
If z liters of water is measurable, you must has z liters of water contained within one or both Buc Kets by the end.
Operations allowed:
- Fill any of the jugs completely with water.
- 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.
Example 1: (from the famous " Die Hard" example)
Input:x = 3, y = 5, z = 4output:true
Example 2:
Input:x = 2, y = 6, z = 5output:false
Credits:
Special thanks to @vinod23 for adding this problem and creating all test cases.
Analysis:
It is a number theory problem.
Https://discuss.leetcode.com/topic/49238/math-solution-java-solution/2
Solution:
Public classSolution { Public BooleanCanmeasurewater (intXintYintz) {if(X+y < Z)return false; if(x==z | | y==z | | x+y==z)return true; returnZ%GCD (x, y) ==0; } Public intGCD (intXinty) { while(x%y!=0){ inttemp =x; X=y; Y= temp%y; } returny; }}
Leetcode-water and Jug problem