leetcode 29 link
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.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Note:
Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
这题 就是 用 加减法 实现 两数相除 ( 就是只能用 位运算 )
比如 10 /3 就是 10-3-3-3 =1 < 3 的过程, divisor 3 被减去了3次, 所以商为3.
如果 每次只减去 divisor 复杂度 为 O(n),
显然可以优化到 O(logn)。 就是 加减的过程中, 让divisor 不断 乘2 或者除2.
这里我简单写了下。。
#include <cmath>
class Solution {
public:
int divide(int dividend, int divisor) {
// 整数减法
long dividend_l = dividend;
long ret = 0;
int count = 1;
long divisor_change = divisor;
// 符号
bool flag = (dividend>0 &&divisor>0 )||(dividend<0 && divisor<0)? true:false;
// abs
dividend_l = abs(dividend_l);
divisor_change = abs(divisor_change);
// dividend <= divisor || divisor = 1
if(dividend_l < divisor_change){ return 0;}
if(dividend_l == divisor_change) { return flag?1:-1;}
if(divisor_change == 1){
if(flag){
return dividend_l> pow(2,31)-1 ? pow(2,31)-1 : dividend_l;
}
return -dividend_l;
}
// nlogn divisor>>1
while(dividend_l >= divisor_change){
dividend_l-=divisor_change;
ret+=count;
count<<=1; divisor_change<<=1;
}
while( dividend_l >=abs(divisor)){
count>>=1;divisor_change>>=1;
if(dividend_l >=divisor_change){
dividend_l-=divisor_change;
ret+=count;
}
}
// positive overflow
ret = flag?ret: -ret;
return ret> pow(2,31)-1? pow(2,31)-1 : ret;
}
};