#29
Medium Algorithms Divide two integers
Math Bit Manipulation
19.4% acceptance
Jan 12, 2026
6062
15266
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.
Return the quotient after dividing dividend by divisor.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn divide(dividend: i32, divisor: i32) -> i32 {
// Handle overflow case
if dividend == i32::MIN && divisor == -1 {
return i32::MAX;
}
// Determine the sign of the result
let negative = (dividend < 0) ^ (divisor < 0);
// Work with absolute values using i64 to avoid overflow
let mut dvd = (dividend as i64).abs();
let dvs = (divisor as i64).abs();
let mut quotient = 0i64;
// Subtract divisor from dividend using bit shifting
while dvd >= dvs {
let mut temp = dvs;
let mut multiple = 1i64;
// Find the largest multiple of divisor that fits
while dvd >= (temp << 1) {
temp <<= 1;
multiple <<= 1;
}
dvd -= temp;
quotient += multiple;
}
// Apply sign and clamp to i32 range
if negative {
(-quotient).max(i32::MIN as i64) as i32
} else {
quotient.min(i32::MAX as i64) as i32
}
}
}