Divide Two Integers
https://leetcode.com/problems/divide-two-integers/description/
Thoughts
Code
/*
* @lc app=leetcode id=29 lang=cpp
*
* [29] Divide Two Integers
*/
// @lc code=start
class Solution {
public:
int divide(int dividend, int divisor) {
bool neg = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0);
long d = labs(dividend), s = labs(divisor), res = 0;
while (d >= s) {
long tmp = s, count = 1;
while (tmp <= d) {
tmp <<= 1;
count <<= 1;
}
res += count >> 1;
d -= tmp >> 1;
}
if (neg) res = ~res + 1;
return res > INT_MAX ? INT_MAX : (int) res;
}
};
// @lc code=end
Analysis
Last updated