1. 程式人生 > >LeetCode Week 9

LeetCode Week 9

29. Divide Two Integers

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.
在這裡插入圖片描述

solutions:

本題意是給定兩個整數除數和除數,不使用乘法、除法和模除以兩個整數。除以除數後的商。整數除法應截斷為零。

一開始我們可以很容易的想到使用減法,但是也很必然的超時錯誤。對其做優化,由於不能使用乘法,所以使用代替的位運算來進行優化。

class Solution {
public:
    int divide(int dividend, int divisor) {
        if(dividend == -2147483648 && divisor == -1)
        return 2147483647;
        long long a = abs((double)dividend);  
        long long b = abs((double)divisor);  
        int result = 0;
        while(a >= b)
        {
            long long c = b;
            for(int i = 0;c <= a ;i++)
            {
                a -= c;
                result += 1<<i;
                c = c<< 1;
            }
        }
        if((dividend < 0)^(divisor < 0))
        result = -result;
        return (int)result;
    }
};

在這裡插入圖片描述