Accepted 4ms c++ solution


  • 1
    M
    class Solution {
    public:
        int divide(int dividend, int divisor) {
            if (divisor == 0) return INT_MAX;
            if (divisor == 1) return dividend;
            if (divisor == -1) return dividend == INT_MIN ? INT_MAX : -dividend;
            unsigned int a = dividend >= 0 ? dividend : -dividend;
            unsigned int b = divisor >= 0 ? divisor : -divisor;
            unsigned int result = 0;
            while (true) {
                unsigned int c = b, k = 1;
                while (a > c) {
                    c = c << 1;
                    k = k << 1;
                }
                if (a < c) {
                    c = c >> 1;
                    k = k >> 1;
                }
                if (k == 0) break;
                a = a - c;
                result += k;
            }
            int sign = (dividend^divisor)>>31 ? -1 : 1;
            return sign==1 ? result : -result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.