Leetcode 29. Divide Two Integers

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Divide Two Integers

2. Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int divide(int dividend, int divisor) {
if(dividend == INT_MIN && divisor == -1) {
return INT_MAX;
}
int sign = (dividend > 0) ^ (divisor > 0)?-1:1;
long x = labs(dividend);
long y = labs(divisor);
int result = 0;
int power= 1;
while(x >= y) {
long temp = y;
power = 1;
while(x >= (temp << 1)) {
temp <<= 1;
power <<= 1;
}
x -= temp;
result += power;
}
return sign>0?result:-result;
}
};

Reference

  1. https://leetcode.com/problems/divide-two-integers/description/
如果有收获,可以请我喝杯咖啡!