Clean code with explanation and Chinese comment


  • 1
    W
    // 1,我们可以以一种代价比较低的方式累加divisor到非常接近dividend的一个值x,并在此过程
    //    中记录累加次数,然后记录差值dividend = dividend - x
    // 2,如果dividend已经比divisor小了,则我们返回累加的次数,否则继续步骤1
    // we could use a "cheap" addition(i.e. continously double divisor) to do it:
    // 1, we continously double divisor until it is close enough to divident, we record this fianal number
    //    as x and the total times we do the "cheap" addition as c, also we record dividend = dividend - x.
    // 2, if dividend is smaller than divisor, we return c, else we do step 1 again.
    public class Solution {
        
        public int divide(int dividend, int divisor) {
            // 如果除数为0或者结果为2147483648则溢出
            // If the divisor is 0 or the result is 2147483648 then it overflows
            if(divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) return Integer.MAX_VALUE;
            // 将除数和被除数符号统一,这样方便操作,因为-214748364没有对应的正数,因此我们将除数被除数
            // 都转化为负数。
            // Convert dividend and divisor both to negetive or positive, so we can do
            // addition without bothering by the signs, because -2147483648 doesn't have the
            // positive counterpart, so we convert them to negetive.
            int dividend2 = dividend < 0 ? dividend : -dividend;
            int divisor2 = divisor < 0 ? divisor : -divisor;
            int c = 0;  // 用于记录总的累加次数 count the totally addition operation
            
            // 重复步骤1,直到满足退出条件
            // Do step 1 until it can return
            while(dividend2 <= divisor2) {
                // j用于记录当前循环中累加的次数,z是累加的和
                // j counts the addition opration in this loop, z records the sum we get
                int j = 1; z = divisor2;
                // 每次讲z扩大两倍,这种累加方式代价比较低
                // Double z until it is colse enough to dividend
                for( ;(z << 1) < 0 && (z << 1) >= dividend2; z = z << 1, j = j << 1)
                    ;
                c += j; // 将当前循环的累加次数记录到总累加次数中
                dividend2 = dividend2 - z;
            }
            return (divisor ^ dividend) >= 0 ? c : -c;
        }
    }

Log in to reply
 

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