leetcode365. Water and Jug Problem

Posted godlei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode365. Water and Jug Problem相关的知识,希望对你有一定的参考价值。

题目描述:

You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly zlitres using these two jugs.

Operations allowed:

  • Fill any of the jugs completely.
  • Empty any of the jugs.
  • Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.

解题分析:

这是我本科时算法课上到一道经典题。两个瓶子可能量出的水是两个瓶子容量最大公约数的倍数。所以只要判断z是否可以被x,y的最大公约数整除即可。

具体代码:

 1 public class Solution {
 2       public static boolean canMeasureWater(int x, int y, int z) {
 3         int n=Math.max(x, y);
 4         int m=Math.min(x, y);
 5         x=n;
 6         y=m;
 7         if(z>x)
 8             return false;
 9         if(z==x||z==y)
10             return true;
11         n=fun(x,y);
12         return z%n==0;
13     }
14     //求x,y的最大公约数
15     public static int fun(int x,int y){
16         if(x%y==0)
17             return y;
18         while(x%y!=0){
19             int m=Math.max(x-y, y);
20             int n=Math.min(x-y, y);
21             x=m;
22             y=n;
23         }
24         return y;
25     }
26 }

 

以上是关于leetcode365. Water and Jug Problem的主要内容,如果未能解决你的问题,请参考以下文章

365. 水壶问题

365. Water and Jug Problem

LeetCode-Water and Jug Problem

365. 水壶问题(gcd)

water-and-jug-problem

Leetcode: Water and Jug Problem && Summary: GCD求法(辗转相除法 or Euclidean algorithm)