class Solution { public: int divide(int dividend, int divisor) { long long a = abs((long long)dividend); long long b = abs((long long)divisor); int sign = (dividend > 0 ^ divisor > 0) ? -1 : 1; //Dealwith positive or negative long long result = 0; while(a >= b){ long long c = b; for(int i = 0;a >= c;++i,c <<= 1){ a -= c; result += 1 << i; } } result *= sign; // If it is overflow, returnMAX_INT. if (result > INT_MAX || result < INT_MIN){ result = INT_MAX; } returnresult; } };
Solution 2: Exponentionalize (C++)
Time: O(log n) Test: 8 ms
This is a smart solution inspired by dimal97psn @ Leetcode. The core idea here is to transfer the division equation: