Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
基本的用减法操作可以实现除法,但是速度较慢。为了加快速度,每次将除数和结果加倍。
int divide(int dividend, int divisor) { //C++ if(dividend == 0) return 0; if(divisor ==0 || dividend == -2147483648&&divisor ==-1) return 2147483647; bool sameFlag = true; if((dividend >0 && divisor <0 )||(dividend <0 && divisor >0)) sameFlag = false; long tmpdividend = (dividend >0)? dividend : -(long)(dividend); long tmpdivisor = (divisor >0) ? divisor : -(long)(divisor); int result = 0; while(tmpdividend >=tmpdivisor){ int size = 1; long t = tmpdivisor; while(tmpdividend >= t) { result +=size; tmpdividend -= t; t = t+t; size = size+size; } } if(!sameFlag) result = -result; return result; }
[leetcode] 29 Divide Two Integers
原文地址:http://blog.csdn.net/chenlei0630/article/details/43150571