博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
365. Water and Jug Problem
阅读量:4598 次
发布时间:2019-06-09

本文共 1754 字,大约阅读时间需要 5 分钟。

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 z litres using these two jugs.

If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.

Operations allowed:

  • Fill any of the jugs completely with water.
  • 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.

 

Example 1: (From the famous )

Input: x = 3, y = 5, z = 4Output: True

 

Example 2:

Input: x = 2, y = 6, z = 5Output: False

 

Credits:

Special thanks to  for adding this problem and creating all test cases.

 

/**

* Math problem
* 能测的体积是两个瓶子最大公约数的倍数
* 比较麻烦的是0 的情况!!
*/

/** * Math problem * 能测的体积是两个瓶子最大公约数的倍数 *  比较麻烦的是0 的情况!! * 可用数论的知识 Bézout's identity 求最大公约数*/public class Solution {    public boolean canMeasureWater(int x, int y, int z) {        if(x+y < z) return false;        if(x == 0 && y == 0 && z == 0) return true;        if(x == 0 || y == 0 && z != 0) return false;        return z % gcd1(x,y) == 0;    }        // Bézout's identity    //let a and b be nonzero integers and let d be their greatest common divisor. Then there exist integers x and y such that ax+by=d    public int gcd1(int x, int y){          while(y != 0){            int temp = y;            y = x % y;            x = temp;        }        return x;    }        public int gcd2(int x, int y){        int res = 1;        int end = Math.min(x, y);        if(end == 1) return 1;        for(int i = 2; i <= end; i++){            if(x % i == 0 && y % i == 0)                res = i;        }        return res;    }}

 

转载于:https://www.cnblogs.com/joannacode/p/6109005.html

你可能感兴趣的文章
MySQL详解(18)-----------分页方法总结
查看>>
bzoj 4595 激光发生器
查看>>
multi cookie & read bug
查看>>
js时间转换
查看>>
(转载) Android Studio你不知道的调试技巧
查看>>
POJ2231 Moo Volume 递推 C语言
查看>>
struts2类型转换的具体流程
查看>>
Hdu 1203 I NEED A OFFER!
查看>>
php文件上传类
查看>>
CF219D Choosing Capital for Treeland
查看>>
luogu P3809 【模板】后缀排序
查看>>
Red Gate 破解
查看>>
JVM 调优工具
查看>>
SCTF 2014 pwn题目分析
查看>>
集合以及特殊集合
查看>>
USACO 2.2 Runaround Numbers
查看>>
利用 force index优化sql语句性能
查看>>
Matlab画图-非常具体,非常全面
查看>>
365. Water and Jug Problem
查看>>
SQL数据库数据检索top和distinct
查看>>