Divide two integers without using multiplication, division and mod operator.
计算两个数的商,不能使用乘、除、取余操作
class Solution { public: int divide(int dividend, int divisor) { if(divisor==0 || dividend==0)return 0; if(divisor==1)return dividend; if(divisor==-1)return 0-dividend; bool isNegative=false; if((dividend<0&&divisor>0)||(dividend>0&&divisor<0))isNegative=true; //判断正负 long long dend=dividend; long long dsor=divisor; long long totalSum=0; //为了防止越界情况的发生,使用long long类型 long long sum=0; int totalCount=0; int count=0; if(dend<0)dend=abs(dend); //取正 if(dsor<0)dsor=abs(dsor); while(sum+dsor<=dend-totalSum){ count=1; sum=dsor; while(sum+sum<=dend-totalSum){ sum+=sum; count+=count; } totalSum+=sum; totalCount+=count; sum=0; count=0; } if(isNegative)return 0-totalCount; else return totalCount; } };
LeetCode: Divide Two Integers [028],布布扣,bubuko.com
LeetCode: Divide Two Integers [028]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26065835