Leetcode: 29. Divide Two Integers

Description

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

If it is overflow, return MAX_INT.

思路

  • 不允许用乘法,除法和取模
  • 除法可以使用减法实现
  • 如果每一次单个单个减的话,太慢。所以用移位来增加每一次减的数
  • 比如19/2,首先 2 << 3 = 16, res += 1 << 3 = 8;
  • 然后 19 - 16 = 3; 3 / 2 , res += 1 << 0 = 9;
  • 最后 3 - 2 = 1, 1/2 = 0, 所以 res = 9
  • 主要是边界值的考虑
    • -2147483648 / -1 = 2147483647
    • -2147483648 / -1 = -2147483648
    • ...
  • 代码打了太多补丁了。。

代码

class Solution {
public:
    int divide(int dividend, int divisor) {
        
        if(divisor == INT_MIN && dividend == INT_MIN) return 1;
        if(divisor == INT_MIN || dividend == 0) return 0; 
        if(divisor == 0) return INT_MAX;
        
        bool isNegative = false, isINT_MIN = false;
        if(dividend < 0){
            isNegative = !isNegative;
            if(dividend == isINT_MIN)
                isINT_MIN = true;
            else dividend = -dividend;
        }
        
        if(divisor < 0){
            isNegative = !isNegative;
            divisor = -divisor;
        }
        
        int res = 0, tmp = 0, count = 0;
        while(dividend >= divisor || dividend == INT_MIN){
            tmp = divisor;
            count = 0;
            while(1){
                int next = tmp << 1;
                if(tmp > next) break;
                
                if((dividend > next) || (dividend == INT_MIN && INT_MAX > next)){
                    tmp = next;
                    count++;
                }
                else break;
            }
            
            if(dividend >= tmp || dividend == INT_MIN)
                res += 1 << count;
           
            if(isINT_MIN){
                dividend += tmp;
                dividend = -dividend;
                isINT_MIN = false;
            }
            else
                dividend -= tmp;
        }
        
        if(res < 0)
            return isNegative ? res : INT_MAX;
        else 
            return isNegative ? -res :  res;
    }
};
posted @ 2017-05-08 14:58  JeffLai  阅读(158)  评论(0编辑  收藏  举报