Solution share, 5ms, no long, no explicit == extreme case test


  • -2
    B
    int divide(int dividend, int divisor) {
        int values[32] = {divisor};
        int doubles[32] = {1};
        for (int i = 0; i < 30; i++) {
            doubles[i+1] = doubles[i] + doubles[i];
        }
        doubles[31] = INT_MAX;
        int begin = 0, count = 0;
        
        if (divisor > 0) {
            values[0] = divisor;
            for (int i=0; i<31; i++) {
                if (values[i] > values[i] + values[i]) break;
                begin++;
                values[i+1] = values[i]+values[i];
            }
            if (dividend > 0) {
                for (int i=begin; i>-1; i--) {
                    if (dividend >= values[i]) {
                        dividend -= values[i];
                        count += doubles[i];
                    }
                }
            } else if (dividend < 0) {
                for (int i=begin; i>-1; i--) {
                    if (dividend <= -values[i]) {
                        dividend += values[i];
                        count -= doubles[i];
                    }
                }
                while (dividend <= -values[0]) {
                    dividend += values[0];
                    count -= doubles[0];
              }
            } else {
                return 0;
            }
        } else if (divisor < 0) {
            values[0] = divisor;
            for (int i=0; i<31; i++) {
                if (values[i] < values[i] + values[i]) break;
                begin++;
                values[i+1] = values[i]+values[i];
            }
            if (dividend > 0) {
                for (int i=begin; i>-1; i--) {
                    if(-dividend <= values[i]) {
                        dividend += values[i];
                        count -= doubles[i];
                    }
                }
            } else if (dividend < 0) {
                for (int i=begin; i>-1; i--) {
                    if (dividend <= values[i]) {
                        dividend -= values[i];
                        count += doubles[i];
                    }
                }
            } else {
                return 0;
            }
        } else {
            printf("Division by zero! Exiting...\n");
            exit(EXIT_FAILURE);
        }
        return count;
    }

Log in to reply
 

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