题目来源:leetcode
题目,写一个除法,不用操作符模运算,除法等。
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.
思路:
根据最原始的除法运算,计算的时候,
1、先看有没有意义(分母为0、分子超限)
2、再看符号,分子分母是不是相同的
3、看分子是几倍的分母,减去,再想办法。
代码:
class Solution {
public:
int divide(int dividend, int divisor) {
if(!divisor || dividend==INT_MIN && divisor==-1) return INT_MAX;
int res = 0;
int sign =( (divisor<0) ^ (dividend<0) )? -1:1;
long long dvd = labs(dividend),dvs = labs(divisor);
while(dvd>=dvs)
{
long long tmp = dvs, muli = 1;
while(dvd>=(tmp<<1))
{
tmp<<=1;
muli<<=1;
}
res +=muli;
dvd -=tmp;
}
return sign==1?res:-res;
}
};