将两个整数相除,要求不使用乘法、除法和 mod 运算符。如果溢出,返回 2147483647 。
class Solution {public: int divide(int dividend, int divisor) { // Write your code here const int OVER_FLOW = 2147483647; long long divd = dividend; long long divr = divisor; if (divr == 0) { return OVER_FLOW; } int flag = 1; if (divd < 0 && divr > 0 || divd > 0 && divr < 0) { flag = -1; }
divd = abs(divd); divr = abs(divr); long long ret = 0; while (divr <= divd) { long long cnt = 1; long long tmp = divr; while (tmp <= divd) { divd -= tmp; ret += cnt; cnt <<= 1; tmp <<= 1; } } ret *= flag; if (ret > INT_MAX || ret < INT_MIN) { return OVER_FLOW; } return ret; } };