The task
Implement division of two positive integers without using the division, multiplication, or modulus operators. Return the quotient as an integer, ignoring the remainder.
My solution
const division = (dividend, divisor) => {
let remainder = null;
let quotient = 1;
const sign = ((dividend > 0 && divisor < 0) ||
(dividend < 0 && divisor > 0)) ?
~1 : 1;
let tempdividend = Math.abs(dividend);
let tempdivisor = Math.abs(divisor);
if (tempdivisor === tempdividend) {
remainder = 0;
return sign;
} else if (tempdividend < tempdivisor) {
remainder = dividend < 0 ?
sign < 0 ? ~tempdividend : tempdividend :
tempdividend;
return 0;
}
while (tempdivisor << 1 <= tempdividend) {
tempdivisor = tempdivisor << 1;
quotient = quotient << 1;
}
quotient = dividend < 0 ?
(sign < 0 ? ~quotient : quotient) + division(~(tempdividend-tempdivisor), divisor) :
(sign < 0 ? ~quotient : quotient) + division(tempdividend-tempdivisor, divisor);
return quotient;
}
division(-1,1)
returns-2,
-2 / -1` returns3
and worst any value divide 0 does not return at all. \$\endgroup\$ – Blindman67 Apr 18 '19 at 23:50