Leetcode-water and Jug problem

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.