Divide Two Integers LeetCode solution in Rust

1
impl Solution {
2
pub fn divide(dividend: i32, divisor: i32) -> i32 {
3
let is_neg = (dividend < 0) ^ (divisor < 0);
4

5
let mut p = if dividend > 0 { -dividend } else { dividend };
6
let q = if divisor > 0 { -divisor } else { divisor };
7

8
// res is the *negative* absolute value of the quotient, in case the quotient is i32::MIN.
9
let mut res = 0;
10

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)) {
15
p -= q << shift;
16
res += -1 << shift; // Not "res -= 1 << shift;" which may cause overflow.
17
}
18
}
19

20
if is_neg {
21
res
22
} else if res == i32::MIN {
23
i32::MAX
24
} else {
25
-res
26
}
27
}
28
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0