@@ -0,0 +1,901 @@
+package leetcode.oj.math;%0D%0A%0D%0A/**%0D%0A * Divide two integers without using multiplication, division and mod operator.%0D%0A */%0D%0A%0D%0A// OK%0D%0Apublic class DivideTwoIntegers %0D%0A%7B%0D%0A%09// O(log(dividend))%0D%0A%09public static int divide(int dividend, int divisor) %0D%0A%09%7B%0D%0A%09%09long N = Math.abs((long) dividend);%0D%0A%09%09long D = Math.abs((long) divisor);%0D%0A%09%09%09%09%0D%0A%09%09long R = D;%0D%0A%09%09int i = 0;%0D%0A%09%09while (R %3C%3C 1 %3C= N)%0D%0A%09%09%7B%0D%0A%09%09%09R = R %3C%3C 1;%0D%0A%09%09%09i++;%0D%0A%09%09%7D%0D%0A%09%09%0D%0A%09%09long Q = 0;%0D%0A%09%09while (i%3E=0)%0D%0A%09%09%7B%0D%0A%09%09%09if (N %3E= R)%0D%0A%09%09%09%7B%0D%0A%09%09%09%09N = N - R;%0D%0A%09%09%09%09Q += 1 %3C%3C i;%0D%0A%09%09%09%7D%0D%0A%09%09%09R = R %3E%3E 1;%0D%0A%09%09%09i --;%0D%0A%09%09%7D%0D%0A%09%09%0D%0A%09%09return (int) (((dividend %3E 0) %5E (divisor %3E 0)) ? -Q : Q);%0D%0A%09%7D%0D%0A%09// Idea:%0D%0A%09// Q = 5 represented in binary : 101, calculate each bit%0D%0A%09// similar to long division%0D%0A%09// Mistakes:%0D%0A%09// 1. Consider overflow!%0D%0A%09%0D%0A%09public static void main (String%5B%5D args)%0D%0A%09%7B%0D%0A%09%09System.out.println(divide(-2147483648, 1));%0D%0A%09%09System.out.println(divide(50, 7));%0D%0A%09%7D%0D%0A%7D%0D%0A

Divide Two Integers