[LeetCode]29. Divide Two Integers

不适用乘除做除法

Posted by JinFei on March 27, 2020

题目描述

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.

Example1:

  Input: dividend = 10, divisor = 3
    Output: 3

Example2:

  Input: dividend = 7, divisor = -3
    Output: -2

Note:

  1. Both dividend and divisor will be 32-bit signed integers.
  2. The divisor will never be 0.
  3. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

解题思路

  • a / b 不能使用乘除取余
  • 可以转换成log来实现相应的除的功能 a / b = e ^ {ln(a) - ln(b)}
  • 中途需要判断 是否溢出
class Solution {
public:
    int divide(int dividend, int divisor) {
        int sign = (dividend < 0 ^ divisor < 0) ? -1 : 1;
        long ldividend = labs(dividend);
        long ldivisor = labs(divisor);
        
        long res = exp(log(ldividend) - log(ldivisor));
        if(res > INT_MAX){
            return sign == -1 ? INT_MIN : INT_MAX;
        }
        return res * sign;
    }
};