Question Link

https://leetcode.com/problems/divide-two-integers/

Question Description

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

Simulation

Solution 1: Brutal - Minus

Input: Divident = 7, Divisor = -3
This approach is based on the idea the division is simply multiple minues. Then, we will need to handle the edge case of minues number.
Leetcode 29. Divide Two Integers - 图1

Solution 2: Bit + Greedy

Input: Divident = 10, Divisor = 3
Leetcode 29. Divide Two Integers - 图2

Implementation

Solution 1: Brutal - Minus

Below solution doesn’t handle any edge case of overflow…

  1. public int divide(int dividend, int divisor) {
  2. if (divisor == 1) {
  3. return dividend;
  4. }
  5. boolean isPositive = false;
  6. int count = 0;
  7. if ((dividend >= 0 && divisor >= 0) || (dividend < 0 && divisor < 0))
  8. isPositive = true;
  9. if (dividend < 0)
  10. dividend *= -1;
  11. if (divisor < 0)
  12. divisor *= -1;
  13. while (dividend >= divisor) {
  14. dividend -= divisor;
  15. count++;
  16. if (count == Integer.MAX_VALUE) {
  17. break;
  18. }
  19. }
  20. return isPositive ? count : count * -1;
  21. }

Solution 2: Bit + Greedy

public int divide(int dividend, int divisor) {
    boolean isNegative = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) ? true : false;
    long absDividend = Math.abs((long) dividend);
    long absDivisor = Math.abs((long) divisor);
    long result = 0;
    while(absDividend >= absDivisor){
        long tmp = absDivisor, count = 1;
        while(tmp <= absDividend){
            tmp <<= 1;
            count <<= 1;
        }
        result += count >> 1;
        absDividend -= tmp >> 1;
    }
    return  isNegative ? (int) ~result + 1 : result > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) result;
}