28. Divide Two Integers

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

---

public class Solution {
    public int divide(int dividend, int divisor) {
        
        boolean sign1 = dividend >=0;
        boolean sign2 = divisor >=0;
        
        long a = Math.abs((long)dividend);
        long b = Math.abs((long)divisor);
        long rst = 0;
        
        while (a >= b) {
            long c = b;
            for (int i = 0; c <= a; ++i, c <<= 1) {
                a -= c;
                rst += 1 << i;
            }
        }

        if (sign1 ^ sign2)
            rst = -rst;
            
        return  (int)rst;
    }
        
}

 

posted @ 2013-09-02 05:24  LEDYC  阅读(130)  评论(0)    收藏  举报