# 8ms c++ solution

• firstly, we can finish division by position move operation. let divisor move to be the max number less than dividend, then subtract dividend by the max number and result plus move times. let the max number do move right operation, compare it with new dividend, if the later is bigger, then plus the move times. repeat this until the move times is zero.
second, we consider sign operation. easily, we turn dividend an divisor to be minus number.
for example:
32 5
32 20 4
12 10 2
2 5 0
result : 4 + 2 = 6

``````class Solution {
public:
int divide(int dividend, int divisor) {
int result = 0;
int sign = 1;
if (divisor == 0)
return INT_MAX;
if (dividend > 0) {
dividend = -dividend;
sign = -sign;
}
if (divisor > 0) {
divisor = -divisor;
sign = -sign;
}
if (dividend > divisor)
return 0;
int tmp = divisor;
int n = -1;
int k = 1;
while ((dividend>>1) <= tmp) {
n <<= 1;
tmp <<= 1;
++k;
}
//cout << "n:" << n << " tmp:" << tmp << endl;
while (k > 0) {
if (dividend <= tmp)
{
dividend -= tmp;
result += n;
}

tmp >>= 1;
n >>= 1;
--k;
}
if (sign > 0) {
if (result == INT_MIN)
return INT_MAX;
result = -result;
}
return result;
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.