标签:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
使用long long避免溢出,注意dividend=0x8000000时容易产生溢出.
1 int divide(int dividend, int divisor) 2 { 3 int signf = dividend > 0 ? 1 : -1; 4 int signs = divisor > 0 ? 1 : -1; 5 long long ldividend = dividend > 0 ? dividend : -(long long)dividend; 6 long long ldivisor = divisor > 0 ? divisor : -(long long)divisor; 7 long long quotient = 0; 8 9 while (ldividend >= ldivisor) 10 { 11 long long tdivisor = ldivisor; 12 long long tquotient = 1; 13 while ((tdivisor << 1) < ldividend) 14 { 15 tdivisor <<= 1; 16 tquotient <<= 1; 17 } 18 quotient += tquotient; 19 ldividend -= tdivisor; 20 } 21 if (signf == signs) 22 return quotient > INT_MAX ? INT_MAX : quotient; 23 else 24 return -quotient; 25 }
leetcode 29. Divide Two Integers
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4268386.html