首页 > 代码库 > Divide Two Integers

Divide Two Integers

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


public class Solution {
  public int divide(int dividend, int divisor) {
    int sign = 1;
    if (dividend < 0) {
      sign *= -1;
    }
    if (divisor < 0) {
      sign *= -1;
    }

    long big = Math.abs((long) dividend);
    long small = Math.abs((long) divisor);
    long temp = small;
    long midres = 1;
    while (temp < big) {
      temp <<= 1;
      midres <<= 1;
    }

    int ret = 0;
    while (temp >= small) {
      while (big >= temp) {
        big -= temp;
        ret += midres;
      }
      temp >>= 1;
      midres >>= 1;
    }
    return ret * sign;
  }
}