#include <iostream>
#include <limits.h>
int divide(int dividend, int divisor) {
// Handle edge cases
if (divisor == 0) {
throw std::invalid_argument("Divisor cannot be zero.");
}
if (dividend == INT_MIN && divisor == -1) {
return INT_MAX; // Overflow case
}
// Determine the sign of the result
bool negative = (dividend < 0) ^ (divisor < 0);
// Convert both numbers to positive
long long absDividend = std::abs(static_cast<long long>(dividend));
long long absDivisor = std::abs(static_cast<long long>(divisor));
int result = 0;
// Perform the division using bit manipulation
while (absDividend >= absDivisor) {
long long temp = absDivisor, multiple = 1;
while (absDividend >= (temp << 1)) {
temp <<= 1;
multiple <<= 1;
}
absDividend -= temp;
result += multiple;
}
return negative ? -result : result;
}
int main() {
int dividend = 42;
int divisor = 6;
try {
int result = divide(dividend, divisor);
std::cout << "Result: " << result << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << e.what() << std::endl;
}
}
/*
run:
Result: 7
*/