LeetCode Divide Two Integers

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

If it is overflow, return MAX_INT.

 

 1 public class Solution {
 2     public int divide(int dividend, int divisor) {
 3         if (dividend == 0) {
 4             return 0;
 5         }
 6 
 7         long a=dividend,b=divisor;
 8         boolean isNeg=false;
 9         if (dividend < 0) {
10             isNeg=!isNeg;
11             a=-a;
12         }
13         if (divisor < 0) {
14             isNeg = !isNeg;
15             b = -b;
16         }
17         long i=0;
18         if(b==1) {
19            i=a; 
20         }else
21         {
22             while (a >= b) {
23                 long temp = b;
24                 int k=1;
25                 while (temp + temp <= a) {
26                     k = k << 1;
27                     temp = temp + temp;
28                 }
29                 i = i | k;
30                 a = a - temp;
31             }            
32         }
33 
34         if (isNeg) {
35             i = -i;
36         }
37         if (i > Integer.MAX_VALUE || i < Integer.MIN_VALUE) {
38             return Integer.MAX_VALUE;
39         }        
40         return (int)i;
41     }
42 }

 

posted @ 2015-01-11 23:05  birdhack  阅读(115)  评论(0编辑  收藏  举报