【Leetcode】【Medium】Divide Two Integers

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

If it is overflow, return MAX_INT.

 

解题思路:

模拟除法运算,但是不能试用 * / % 操作。

 

先思考边界条件,再开始做题:

0、除数为0无意义,需要和出题人沟通此边界是否存在(leetcode中并未考察除数为0的情况,默认除数不为0);

1、传入被除数/除数两个int做除法,什么情况返回值overflow:被除数为-2147483648,除数为-1,结果2147483648越界,此时按题目要求,应该返回INT_MAX。

2、在计算被除数包含多少个除数的过程中,需要不停的累加除数直到累加值超过被除数,此时累加值不可控,可能越界。因此应该使用long long 类型进行运算(32位/64位系统都适用)。

 

想好以上需要注意的边界条件后,使用二分查找的思路:

例如100 ÷ 7:

1、可先对除数7进行左移操作,7->14->28->56->112,112大于100,停止左移,左移倍数为8;

2、100 - 56 = 44,则继续计算44 ÷ 7,对7左移,7->14->28->56,56大于44,停止左移,左移倍数为4;

3、44 - 28 = 16,计算16 ÷ 7,左移倍数2;

4、16 - 14 = 2, 此时2 < 7, 左移倍数0,停止运算;

结果为 8 + 4 + 2 = 14.

 

代码编写过程中,注意被除数和除数的符号。

代码:

 1 class Solution {
 2 public:
 3     int divide(int dividend, int divisor) {
 4         if (dividend == INT_MIN && divisor == -1)
 5             return INT_MAX;
 6         
 7         int sign = (dividend > 0 ^ divisor > 0) ? -1 : 1;
 8         long long end = abs((long long)(dividend));
 9         long long sor = abs((long long)(divisor));
10 
11         int ans = 0;
12         while (end >= sor) {
13             long long cur_sor = sor;
14             int count = 1;
15             while (cur_sor + cur_sor <= end) {
16                 cur_sor <<= 1;
17                 count <<= 1;
18             }
19             end -= cur_sor;
20             ans += count;
21         }
22         
23         if (sign > 0)
24             return ans;
25         else 
26             return 0 - ans;
27     }
28 };

 

posted @ 2015-04-09 09:33  胡潇  阅读(192)  评论(0编辑  收藏  举报