<Math> 29 365

29. Divide Two Integers

class Solution {
    public int divide(int dividend, int divisor) {
        if(dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
        long m = (long)dividend, n = (long)divisor;
        int sign = 1, res = 0;
        if(m < 0){
            m = -m;
            sign = -sign;
        }
        if(n < 0){
            n = -n;
            sign = -sign;
        }
        while(m >= n){
            int shift = 0;
            while(m >= n << shift){
                shift++;
            }
            res += (1 <<(shift - 1));
            m -= (n <<(shift - 1));
        }
        return sign * res;
    }
}

365. Water and Jug Problem

class Solution {
    public boolean canMeasureWater(int x, int y, int z) {
    //limit brought by the statement that water is finallly in one or both buckets
    if(x + y < z) return false;
    //case x or y is zero
    if( x == z || y == z || x + y == z ) return true;
    
    //get GCD, then we can use the property of Bézout's identity
    return z%GCD(x, y) == 0;
}

public int GCD(int a, int b){
    while(b != 0 ){
        int temp = b;
        b = a%b;
        a = temp;
    }
    return a;
}
}

猜你喜欢

转载自www.cnblogs.com/Afei-1123/p/12077606.html
365
29
今日推荐