Leetcode-Divide Two Integers

LiBlog發表於2014-12-16

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

If it is overflow, return MAX_INT.

Solution:

 1 public class Solution {
 2     public int divide(int dividend, int divisor) {
 3         if (divisor==0) return Integer.MAX_VALUE;
 4         if (dividend==0) return 0;
 5         if (divisor==1) return dividend;
 6         if (dividend==Integer.MIN_VALUE && divisor==-1) return Integer.MAX_VALUE;
 7 
 8         boolean neg = false;
 9         //change to all negtive number.
10         if (dividend>0){
11             dividend = -dividend;
12             neg = !neg;
13         }
14         if (divisor>0){
15             divisor = - divisor;
16             neg = !neg;
17         }
18 
19         int minDivisor = Integer.MIN_VALUE >> 1;
20         int cur = divisor;
21         int val = 1;
22         while (cur>=minDivisor && cur>dividend){
23             cur <<= 1;
24             val <<= 1;
25         }
26 
27         int res = 0;
28         while (dividend<=divisor){
29             while (cur<dividend){
30                 cur >>= 1;
31                 val >>= 1;
32             }
33             dividend -= cur;
34             res += val;
35         }
36 
37         if (neg) return -res;
38         else return res;
39     }
40 }

 

相關文章