难受啊
考虑越界
考虑dividend为-2^31,用负数移位运算
class Solution { public: int divide(int dividend, int divisor) { if(dividend == divisor) return 1; if(divisor == INT_MIN) return 0; if(dividend==INT_MIN&&divisor==-1) return INT_MAX; if(dividend==INT_MIN&&divisor==1) return INT_MIN; int flag=(dividend>0)^(divisor>0); if (dividend > 0) dividend = -dividend; if (divisor > 0) divisor = -divisor; int n = 0; int count = 0; int temp = abs(divisor); int i; while (dividend <= divisor) { if (n == 31) break; i = -(temp << n); if (dividend > i) //看成正数就是不够减 { n--; if (n < 0) break; } else { dividend = dividend - i; count = count + (1 << n); if (dividend <= i) //设i=1,2,4,8,...2^30 相加为2^31-1,此时n=30,若dividend还剩1,不加判断会导致上面temp<<31,越界 { n++; } } } return flag ? -count : count; } };