29. Divide Two Integers (Medium)

https://leetcode.com/problems/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.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3

Example 2:

Input: dividend = 7, divisor = -3
Output: -2

Note:

  • Both dividend and divisor will be 32-bit signed integers.
  • The divisor will never be 0.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

Hints

Solutions

class Solution {
    public int divide(int dividend, int divisor) {
        if(divisor == 0) return Integer.MAX_VALUE;
        else if(dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
        else if(divisor == 1) return dividend;
        boolean isNegative = ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0));
        dividend = (dividend < 0)? -dividend : dividend;
        divisor = (divisor < 0) ?  -divisor : divisor;
        int sum, result = 0;
        while(true){
            int d1 = divisor;
            sum = 0;
            if(dividend - d1 == 0) {sum += 1; result += sum; break;}
            if(dividend - d1 < 0) break;
            while(dividend - (d1 << 1) > 0){
                d1 <<= 1;
                sum += 1;
            }
            result += (1 << sum);
            dividend = dividend - d1;
        }
        return isNegative ? -result : result;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-09 12:10:47

results matching ""

    No results matching ""