标签:
题目描述:
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:
解题分析:
这是我本科时算法课上到一道经典题。两个瓶子可能量出的水是两个瓶子容量最大公约数的倍数。所以只要判断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