s4553711
5/16/2017 - 2:16 PM

29.cpp

class Solution {
public:
    int divide(int dividend, int divisor) {
        if (dividend == INT_MIN && divisor == -1) {
            return INT_MAX;
        }
        long long a = dividend >= 0 ? dividend : -(long long)dividend;
        long long b = divisor >= 0 ? divisor : -(long long)divisor;
        long long res = 0;
        while (a >= b) {
            long long c = b;
            for (int i = 0; a>=c; i++, c<<=1) {
                //cout << "befre: " << int(1<<i) << ", i = " << i << endl;
                res += 1<<i;
                a -= c;
                //cout << "A: " << a << " ,B: " << b << " ,C: " << c << " ,res:" << res << endl;
            }
        }
        return (dividend ^ divisor) >> 31 ? -res: res;
    }
};