两数相除 - LeetCode

两数相除 - LeetCode_第1张图片

解题思路: 

答案:


/**
 * @param {number} dividend
 * @param {number} divisor
 * @return {number}
 */
var dividend = -2147483648, divisor = 1;
var divide = function (dividend, divisor) {
    let result = 0, sign = 1, mul = 1;
    if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {
        sign = -1;
    }
    dividend = Math.abs(dividend);
    divisor = Math.abs(divisor);

    divisor2 = divisor;

    while (dividend >= divisor2) {
        if (dividend > (divisor2 + divisor2)) {
            divisor2 += divisor2;
            mul += mul;
        }
        dividend -= divisor2;
        result += mul;
    }
    while (dividend >= divisor) {
        dividend -= divisor;
        result += 1;
    }

    if (sign == 1 && result > (Math.pow(2, 31) - 1)) {
        return Math.pow(2, 31) - 1;
    } else if (sign == -1 && result < -Math.pow(2, 31)) {
        return -Math.pow(2, 31);
    }
    if (sign == 1) {
        return result;
    } else {
        return -result;
    }
};
divide(dividend, divisor);

你可能感兴趣的:(javascript)