Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
两数相除,不能用*,/,% 那么只能用位移运算了,注意边界条件防止溢出,代码如下:
1 class Solution { 2 public: 3 int divide(int dividend, int divisor) { 4 int sign1 = dividend > 0 ? 1 : -1; 5 int sign2 = divisor > 0 ? 1 : -1; 6 long long d1 = abs(static_cast<long long>(dividend)); 7 long long d2 = abs(static_cast<long long>(divisor)); 8 int res = 0; 9 while(d1 >= d2){ 10 long long tmp = d2; 11 for(int i = 0; d1 >= tmp; ++i){ 12 d1 -= tmp; 13 tmp <<= 1; 14 res += 1LL << i; 15 } 16 } 17 if(sign1 == sign2){ 18 if(res == INT_MIN) 19 return INT_MAX; 20 return res; 21 }else 22 return res * -1; 23 } 24 };
PS:这题溢出情况相当恶心。