Divide Two Integers

Quesiton from: https://leetcode.com/problems/divide-two-integers/

题目:

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

If it is overflow, return MAX_INT.


题目分析:

  • Integer Overflow, 边界处理, special case:
    • x/0
    • Integer.MIN_VALUE/(-1)
  • Bit Operation
  • O(logn) runtime
  • Attention on Line #39, (num1 >>1) 可以防止 num2 overflow。

面试里,尽量不要使用 long 来处理 Integer Overflow。因为这道题目本身考查的就是各种 Corner Cases 的处理。

 1 public int divide(int dividend, int divisor) {
 2     if(divisor == 0) {
 3         return Integer.MAX_VALUE;
 4     }
 5     
 6     if(dividend == 0) {
 7         return 0;
 8     }
 9     
10     if(divisor == Integer.MIN_VALUE) {
11         return (dividend == divisor)?1:0;
12     }
13     
14     int sign = (((dividend^divisor) >> 31) == 0)? 1:-1;
15     int res = 0;
16     int num1 = 0;
17     int num2 = Math.abs(divisor);
18     
19     
20     if(dividend == Integer.MIN_VALUE) {
21         if(divisor == -1) {
22             return Integer.MAX_VALUE;
23         } else {
24             res = 1;
25             num1 = Math.abs(dividend + num2);
26         }
27     } else {
28         num1 = Math.abs(dividend);
29     }
30     
31     res = helper(num1, num2, res);
32     
33     return (sign>0)?res:-res;
34 }
35 
36 private int helper(int num1, int num2, int res) {     
37     int times = 1;
38 
39     while(num2 <= (num1>>1)) {
40         num2 = num2<<1;
41         times = times<<1;
42     }
43     
44     while(times > 0) {
45         if(num1 >= num2) {
46             num1 -= num2;
47             res += times;
48         }
49         times >>= 1;
50         num2 >>= 1;
51     }
52     
53     return res;
54 }
原文地址:https://www.cnblogs.com/Phoenix-Fearless/p/5097693.html