LeetCode OJ:Divide Two Integers

Divide Two Integers

 

Divide two integers without using multiplication, division and mod operator.


算法思想:

二分

class Solution {
public:
    int divide(int dividend, int divisor) {
         if (dividend == 0 || divisor == 0)
            return 0;

        int sign = 0;
        if ((dividend>0&&divisor<0) || (dividend<0&&divisor>0))
            sign = 1;
        
        long long a = abs((long long) dividend);
        long long b = abs((long long) divisor);
        
        if (b > a)
            return 0;

        long long sum = 0;
        int count = 0;
        int final = 0;
        while (a >= b)
        {
            count = 1;
            sum = b;
            while (sum + sum <= a){ 
                sum += sum;
                count += count;
            }
            a -= sum;
            final += count;
        }
        return sign ? -final:final;
    }
};


你可能感兴趣的:(LeetCode)