This is the 11th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021
Topic describes
Given two integers, dividend and divisor. Dividing two numbers requires no multiplication, division, and mod operators.
Returns the quotient of dividend divided by divisor.
The result of integer division should truncate the decimal part, for example, TRUNCate (8.345) = 8 and TRUNCate (-2.7335) = -2
- Example 1:
Input: Dividend = 10, Divisor = 3 Output: 3 Interpretation: 10/3 = TRUNCate (3.33333..) = truncate(3) = 3Copy the code
- Example 2:
Input: Dividend = 7, Divisor = -3 Output: -2 Explanation: 7/-3 = TRUNCate (-2.33333..) = 2 -Copy the code
- Tip:
Both dividend and divisor are 32-bit signed integers. The divisor is not 0. Assume that our environment can store only 32-bit signed integers with values in the range [−2^31, 2^31 − 1]. In this case, 231 − 1 is returned if the division result overflows.Copy the code
Implementation approach
Two numbers are divided but do not use multiplication, division, or mod operators. The first thing we want to think about is using the for loop to get to the point where divisor*n <= dividend by summing up the divisor, and then returning n, and then committing out of the time limit, so we need to use the in-place operator for this problem.
X >> I is equal to x/2^ I, and x<< I is equal to x*2^ I. Dividend /2^ I ≥ divisor
- Because of the special case where the boundary value overflows we just return the answer
- Define bool to store whether the answer will be negative, and turn both divisor and dividend into positive numbers
- Because of the boundary values we define the interval of I to be 0 to 31, and we compute the value res of 2 to the I by loop summation
- Bool to determine if the answer is negative returns the answer
/ * * *@param {number} dividend
* @param {number} divisor
* @return {number}* /
var divide = function(dividend, divisor) {
const [MIN, MAX] = [-(2 ** 31), 2 ** 31 - 1];
if (dividend === MIN && divisor === -1) return MAX;
if (dividend === MIN && divisor === 1) return MIN;
let bool = false
bool = dividend < 0? ! bool : bool bool = divisor <0? ! bool : boollet res = 0
dividend = Math.abs(dividend)
divisor = Math.abs(divisor)
for (let i = 31; i >=0; i--) {
if (dividend >>> i >= divisor) {
res += 1 << i
dividend -= divisor << i
}
}
res = bool ? -res : res
return res
};
Copy the code