description:
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
Note:
Example:
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
answer:
class Solution {
public:
int divide(int dividend, int divisor) {
if(divisor == 0 || (dividend == INT_MIN && divisor == -1)) return INT_MAX;
//divisor等于-1的话,除法之后因为是整数就会溢出,因为整数范围正负是不对称的
long long m = abs((long long)dividend), n = abs((long long)divisor), res = 0;
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
//^位运算符 异或
if (n == 1) return sign == 1 ? m : -m;
while(m >= n) {
long long t = n, p = 1;
while(m >= (t << 1)) {
t <<= 1;
p <<= 1;
}
res += p;
m -= t;
}
return sign == 1 ? res : -res;
}
};
relative point get√:
hint :
从被除数上减去除数,看能减多少次之后变得不够减。时间复杂度为O(N)
醍醐灌顶!