Divide Two Integers

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.

Example 1:

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

Example 2:

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

Note:

  • Both dividend and divisor will be 32-bit signed integers.
  • The divisor will never be 0.
  • 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.

code

#include <iostream>
using namespace std;

class Solution
{
public:
    int divide(int dividend, int divisor)
    {
        if(!dividend)
            return 0;
        else if(!divisor)
            return INT_MAX;

        bool flag=(!((dividend>0)^(divisor>0)));
        long long dd=abs((long long)dividend);
        long long dr=abs((long long)divisor);
        long long res=0;
        long long remainder=0;
        for(int i=31;i>=0;--i)
        {
            res<<=1;
            remainder<<=1;
            int tmp=(dd>>i)&1;
            remainder+=tmp;
            if(remainder>=dr)
            {
                ++res;
                remainder-=dr;
            }
        }
        res=flag?res:-res;
        if(res>=INT_MAX)
            return INT_MAX;
        else if(res<=INT_MIN)
            return INT_MIN;
        return res;
    }
};

int main()
{
    Solution s;
    cout<<s.divide(7,-3)<<endl;
    return 0;
}

算术表达式

class Solution
{
public:
    int divide(int dividend, int divisor)
    {
        if(!dividend)
            return 0;
        else if(!divisor)
            return INT_MAX;

        long long res=exp(log(abs((long long)dividend))-log(abs((long long)divisor)));
        res=(dividend>0^divisor>0)?-res:res;

        if(res>=INT_MAX)
            return INT_MAX;
        else if(res<=INT_MIN)
            return INT_MIN;
        return res;
    }
};

 

上一篇:华为eSight网络监控平台


下一篇:C++ 处理除法异常