2
pub fn divide(dividend: i32, divisor: i32) -> i32 {3
let is_neg = (dividend < 0) ^ (divisor < 0);5
let mut p = if dividend > 0 { -dividend } else { dividend };6
let q = if divisor > 0 { -divisor } else { divisor };8
// res is the *negative* absolute value of the quotient, in case the quotient is i32::MIN.11
// Here is the magic: the negative divisor(aka q) can left-shift atmost q.leading_ones() - 1 bits before it overflows.12
for shift in (0..q.leading_ones()).rev() {13
// Don't apply "p -= (q << shift)" before overflow checking. Consider p = 0, q << shift = i32::MIN.14
if (p <= (q << shift)) {16
res += -1 << shift; // Not "res -= 1 << shift;" which may cause overflow.22
} else if res == i32::MIN {