Given two integers dividend
and divisor
, divide two integers without using multiplication, division, and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8
and truncate(-2.7335) = -2
.
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, assume that your function returns 231 − 1
when the division result overflows.
Example 1:
Input: dividend = 10, divisor = 3 Output: 3 Explanation: 10/3 = truncate(3.33333..) = 3.
Example 2:
Input: dividend = 7, divisor = -3 Output: -2 Explanation: 7/-3 = truncate(-2.33333..) = -2.
Example 3:
Input: dividend = 0, divisor = 1 Output: 0
Example 4:
Input: dividend = 1, divisor = 1 Output: 1
Constraints:
-231 <= dividend, divisor <= 231 - 1
divisor != 0
class Solution:
def divide(self, a: int, b: int) -> int:
INT_MAX = (1 << 31) - 1
INT_MIN = -(1 << 31)
sign = -1 if a * b < 0 else 1
a = abs(a)
b = abs(b)
tot = 0
while a >= b:
cnt = 0
while a >= (b << (cnt + 1)):
cnt += 1
tot += 1 << cnt
a -= b << cnt
return sign * tot if INT_MIN <= sign * tot <= INT_MAX else INT_MAX
class Solution {
public int divide(int a, int b) {
int sign = 1;
if ((a < 0) != (b < 0)) {
sign = -1;
}
long x = Math.abs((long) a);
long y = Math.abs((long) b);
long tot = 0;
while (x >= y) {
int cnt = 0;
while (x >= (y << (cnt + 1))) {
cnt++;
}
tot += 1L << cnt;
x -= y << cnt;
}
long ans = sign * tot;
if (ans >= Integer.MIN_VALUE && ans <= Integer.MAX_VALUE) {
return (int) ans;
}
return Integer.MAX_VALUE;
}
}
func divide(a int, b int) int {
sign := 1
if a*b < 0 {
sign = -1
}
a = abs(a)
b = abs(b)
tot := 0
for a >= b {
cnt := 0
for a >= (b << (cnt + 1)) {
cnt++
}
tot += 1 << cnt
a -= b << cnt
}
ans := sign * tot
if ans >= math.MinInt32 && ans <= math.MaxInt32 {
return ans
}
return math.MaxInt32
}
func abs(a int) int {
if a < 0 {
return -a
}
return a
}
class Solution {
public:
int divide(int a, int b) {
int sign = 1;
if (a < 0 ^ b < 0) {
sign = -1;
}
auto x = abs(static_cast<long long>(a));
auto y = abs(static_cast<long long>(b));
auto tot = 0ll;
while (x >= y) {
int cnt = 0;
while (x >= (y << (cnt + 1))) {
++cnt;
}
tot += 1ll << cnt;
x -= y << cnt;
}
auto ans = sign * tot;
if (ans >= INT32_MIN && ans <= INT32_MAX) {
return static_cast<int>(ans);
}
return INT32_MAX;
}
};