[LeetCode]029. Divide Two Integers

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


Solution:

1st solution: use the add/subtraction method, but which can not pass the big OJ, such as the input is :2147483647, 1

running time: O(n).

public class Solution {
    public int divide(int dividend, int divisor) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int sign = 1;
        if(dividend < 0){
            sign *= -1;
        }
        if(divisor < 0){
            sign *= -1;
        }
        long tempDividend = Math.abs(dividend);
        long tempDivisor = Math.abs(divisor);
        int count = 0;
        while(tempDividend - tempDivisor >= 0){
            count++;
            tempDividend = tempDividend - tempDivisor;
        }
        return count * sign;
    }
}


2nd solution:

optimize the 1st solution, double the divisor each time.

Running Time: O(lg(n));

note: there's two while loop here, if the temp_divisor bigger than the current dividend, set the temp_divisor to the initial value and start the loop again.


public class Solution {
    public int divide(int dividend, int divisor) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int sign = 1;
        if(dividend < 0){
            sign *= -1;
        }
        if(divisor < 0){
            sign *= -1;
        }
        long a = dividend;
        long b = divisor;
        //must cast to long here for dealing with the Integer.MIN_VALUE
        //because Math.abs(-2147483648) > Integer.MAX_VALUE
        a = Math.abs(a);
        b = Math.abs(b);
        int count = 0;
        while(a >= b){
            long temp = b;
            int multi = 1;
            while(a >= temp){
                count += multi;
                a -= temp;
                temp += temp;
                multi += multi;
            }
        }
        return count * sign;
    }
}

3rd solution: use the bit manipulation, similar to the 2nd solution. To be continued...

running time: O(lg(n)).


4th solution: math formular: exp(log(a) - log(b)); To be continued...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值