Divide two integers without using multiplication, division and mod operator.
思路:不能使用乘法除法以及取模运算来计算两个数相除。主要做法就是,将因子不断乘2(向左移位即可实现),同时结果从1不断移位加倍,等到除数大于被除数一半的时候,就从被除数中减去,将因子个数累加到结果中,再依次反复循环。跳出循环,不断递减的被除数与除数相等,则结果在加1.
class Solution { public: int divide(int dividend, int divisor) { assert(divisor!=0); int result=0,count=0; bool isNeg=false; if((dividend>0&&divisor<0)||(dividend<0&&divisor>0)) isNeg=true; unsigned int tDividend=abs(dividend); unsigned int tDivisor=abs(divisor); unsigned int tmp=0; while(tDividend>tDivisor) { count=1; tmp=tDivisor; while(tDividend>(tmp<<=1)) { count<<=1; } tDividend-=(tmp>>1); result+=count; } if(tDividend==tDivisor) { result++; } return isNeg?(-result):result; } };
Divide Two Integers,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/awy-blog/p/3825446.html