标签:
There couple of edge cases need to remember:
1. The result, absolute value of dividend and divisor. Otherwise, when the record goes out of boundary, the result will be invalid.
2. use long long int as the current value to compare with divd. Because condition is (current << i) <= divd. When the loop break, current may already exceed INT_MAX
1 class Solution { 2 public: 3 int divide(int dividend, int divisor) { 4 unsigned int divd = fabs(dividend), divs = fabs(divisor), result = 0; 5 long long int current = 0; 6 int i = 0; 7 while (divd >= divs) { 8 current = divs; 9 for (i = 0; (current << i) <= divd; i++); 10 result += (1 << (i-1)); 11 divd -= (divs << (i-1)); 12 if (result > INT_MAX) return (dividend < 0 ^ divisor < 0) ? INT_MIN : INT_MAX; 13 } 14 return (dividend < 0 ^ divisor < 0) ? -result : result; 15 } 16 };
LeetCode – Refresh – Divide Two Integers
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/4349380.html