Skip to content

29.divide two integers

难度Medium

刷题内容

原题连接

  • https://leetcode.com/problems/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.

˼· **- ʱ�临�Ӷ�: O(N)*- �ռ临�Ӷ�: O(1)***

�������ֱ���ñ����ķ����϶���ʱ内容描述�����˿ռ任ʱ�䣬内容描述 int ���Ϊ2^31 - 1 内容描述Ĵ�СҲ�ǹ̶��ġ内容描述��ñ内容描述ȶ���һ��res = 0��ÿ�ζ����� res += divisor * 2^n ֱ������dividend �������ٴ� res = divisor * 2^(n-1)��ʼ��ֱ��ij��res + divisor > dividend

class Solution {
public:
    int divide(int dividend, int divisor) {
        if(!dividend)
        return 0;
        long long arr[33];
        arr[0] = 1;
        for(int i = 1;i < 33;++i)
            arr[i] = arr[i - 1] * 2;
        long long temp1 = dividend,temp2 = divisor;
        if(temp1 < 0)
            temp1 *= -1;
        if(temp2 < 0)
            temp2 *= -1;
        long long res,pre = 0,ret = 0;
        int count1 = 0;
        while(1)
        {
            res = pre + arr[count1] * temp2;
            if(res > temp1)
            {
                if(!count1)
                    break;
                pre = pre + arr[count1 - 1] * temp2;
                ret += arr[count1 - 1];
                count1 = 0;
            }
            else
                count1++;
        }
        if(dividend < 0)
            ret *= -1;
        if(divisor < 0)
            ret *= -1;
        if(ret == 2147483648)
            return ret - 1;
        return ret;
    }
};


回到顶部