Java interview questions collection - integer division

Topic: Input two int integers, they perform division calculation and return the quotient, it is required not to use '*', division sign '/' and remainder symbol '%'. Returns the largest integer value when overflow occurs. Assume divisor is not zero. For example, input 15 and 2 and output 15/2, which is 7.

       Violent method: For this topic, the brute force method first thought of by beginners who do not know the algorithm is also feasible: use a loop to make the divisor always subtract the divisor, and subtract the quotient ++ every time. But when the dividend is very large, but the divisor is very small, we can imagine its efficiency.

        Method optimization: When the dividend is greater than the divisor, we continue to compare whether the dividend is greater than twice the dividend, and if so, continue to determine whether the dividend is greater than four times the divisor... If the dividend is at most 2^k times the divisor, then we Directly use the dividend to subtract 2^k times of the divisor. Then repeat the previous steps for the remaining dividends, and the time complexity becomes O(logn).

public int divide(int dividend,int divsor){
    if(dividend == 0x80000000 && divisor == -1){
        return Integer.MAX_VALUE;
    }

    int negative = 2;
    if(dividend > 0){
        negative--;
        dividend = -dividend;//把正数变为负数
    }

    if(divisor > 0){
        negative--;
        divisor = -divisor;//把正数变为负数
    }
    
    int result = divideCore(dividend,divisor);
        return negative == 1 ? -result : result;
}
private int divideCore(int dividend,int divisor){
    int result = 0;//商的大小
    while(dividend <= divisor)
        int value = divisor;
        int quotient = 1;
        while(value >= 0xc0000000 && dividend <= value + value){//因为时负数所以判定用小于
            quotient += quotient;
            dividend -= value;
        }
        result += quotient;
        dividend -= value;
    }
    return result;
}

In the first function, we change both the divisor and the dividend from a positive number to a negative number, which can avoid a situation of overflow, when the dividend is -2^31 when the divisor is -1, because the largest positive number is (2^31-1).

Supongo que te gusta

Origin blog.csdn.net/lijingxiaov5/article/details/122184488
Recomendado
Clasificación