码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】365. Water and Jug Problem

时间:2016-06-24 18:45:32      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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 }

 

【leetcode】365. Water and Jug Problem

标签:

原文地址:http://www.cnblogs.com/godlei/p/5614992.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!