LeetCode 29. Divide Two Integers

29. Divide Two Integers

 
  • Total Accepted: 91862
  • Total Submissions: 575867
  • Difficulty: Medium
  • Contributors: Admin

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

If it is overflow, return MAX_INT. 

Subscribe to see which companies asked this question.

【题目分析】

给定两个整数,返回这两个整数相除的结果,要求不使用乘法和除法运算。如果出现了overflow,则返回MAX_INT.

【思路分析】

1. 什么情况下会出现overflow

当被除数为MIN_INT,除数为-1时。

2. 使用减法来计算

当被除数很大而除数很小时,会导致超时。

3. 使用移位

基本原理是,dividend非常大,所以把它切割成几块,一块一块地和divisor计算商,再把这些商都加起来就可以了。在切割的时候,各个小块是不均匀的。第1块的大小正好是divisor的大小,第2块的大小正好是divisor扩大2倍的大小,第3块的大小正好是divisor扩大2²倍的大小,第4块的大小正好是divisor扩大2³倍的大小......以此类推,直到把dividend分割完毕。

【java代码】

 1 public class Solution {
 2     public int divide(int dividend, int divisor) {
 3         if(dividend == Integer.MIN_VALUE && divisor == -1)
 4             return Integer.MAX_VALUE;
 5         
 6         long x = Math.abs((long) dividend);
 7         long y = Math.abs((long) divisor);
 8         int res = 0;
 9         
10         while(x >= y) {
11             long z = y;
12             for(int i = 0; z <= x; i++) {
13                 x -= z;
14                 res += 1<<i;
15                 z = z<<1;
16             }
17         }
18         
19         return (dividend^divisor) < 0 ? -res : res;
20     }
21 }

 

posted @ 2017-02-19 16:05  Black_Knight  阅读(186)  评论(0编辑  收藏  举报