"Leetcode" 365. Water and Jug problem

Source: Internet
Author: User
Tags greatest common divisor

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

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.