Improved p29 solution

This commit is contained in:
Egor 2024-07-09 11:02:09 +03:00
parent 00dda7fc5c
commit e355d6fa97

View file

@ -1,11 +1,6 @@
pub struct Solution; pub struct Solution;
impl Solution { impl Solution {
// terrible solutionE
// should use approximation using shifts
pub fn divide(mut dividend: i32, mut divisor: i32) -> i32 { pub fn divide(mut dividend: i32, mut divisor: i32) -> i32 {
if dividend == i32::MAX && divisor == i32::MIN {
return 0;
}
if divisor == 1 { if divisor == 1 {
return dividend; return dividend;
} }
@ -15,25 +10,34 @@ impl Solution {
} }
return -dividend; return -dividend;
} }
let mut result = 0; if divisor == dividend {
let is_neg = (dividend < 0) ^ (divisor < 0); return 1;
let mut one = false;
dividend = if dividend == i32::MIN {
one = true;
i32::MAX
} else { dividend.abs() };
divisor = if divisor == i32::MIN { i32::MAX } else { divisor.abs() };
while dividend >= divisor {
dividend -= divisor;
result += 1;
} }
if one && dividend - divisor == -1 { let (mut is_pos, mut quotient) = (true, 0);
result += 1; if dividend >= 0 {
dividend = -dividend;
is_pos = !is_pos;
} }
if is_neg { if divisor >= 0 {
result = -result; divisor = -divisor;
is_pos = !is_pos;
} }
return result; while dividend <= divisor {
let mut shift = 0;
loop {
let shifted = divisor << (shift + 1);
if shifted <= dividend || shifted > 0 {
break;
}
shift += 1;
}
quotient -= 1 << shift;
dividend -= divisor << shift;
}
if is_pos {
quotient = -quotient;
}
return quotient;
} }
} }
@ -60,4 +64,9 @@ mod tests {
fn test4() { fn test4() {
assert_eq!(Solution::divide(-2147483648, -1), 2147483647); assert_eq!(Solution::divide(-2147483648, -1), 2147483647);
} }
#[test]
fn test5() {
assert_eq!(Solution::divide(-2147483648, 3), -715827882);
}
} }