Saturday, July 11, 2015

Divide Two Integers

Divide Two Integers

15%
Accepted
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return 2147483647
Have you met this question in a real interview? 
Yes
Example
Given dividend = 100 and divisor = 9, return 11.
public class Solution {
    /**
     * @param dividend the dividend
     * @param divisor the divisor
     * @return the result
     */
    public int divide(int dividend, int divisor) {
        // Write your code here
        if(divisor == 0)
            return 0;
        if (dividend == Integer.MIN_VALUE && divisor == -1)
            return Integer.MAX_VALUE;
        int sign = 1;
       
        if(dividend < 0){
            sign = -sign;
        }
       
        if(divisor < 0){
            sign = -sign;
        }
        long a = Math.abs((long) dividend);
        long b = Math.abs((long) divisor);
       
        long res = 0;
        while(a >= b){
            long c = b;
            for(int i = 0; c <= a; c <<= 1, i++){
                res += 1 << i;
                a -= c;
            }
        }
        return (int)res*sign;
    }
}

No comments:

Post a Comment