[leetcode]Divide Two Integers

一开始直接用循环减法,会超时,网上看了下,就是除数倍增的方法,这样复杂度由n变成lg n。中间还要注意负数溢出的情况,直接用long了。

public class Solution {

    public int divide(int dividend, int divisor) {

        // Start typing your Java solution below

        // DO NOT write main() function       

        int ans = 0;

        boolean sign = true;

        

        if ((dividend >0 && divisor <0)

            || (dividend < 0 && divisor >0 )) sign = false;

            

        long a = dividend;

        long b = divisor;

        if (a < 0) a = -a;

        if (b < 0) b = - b;

        

        

        while (a >= b)

        {

            int multi = 1;

            long tmp = b;

            while (a >= tmp) {

                a -= tmp;

                ans += multi;

                tmp += tmp;

                multi += multi;

            }

        }

        if (!sign) return -ans;

        else return ans;

    }

}

  

你可能感兴趣的:(LeetCode)