Divide Two Integers leetcode

题目:Divide Two Integers

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

If it is overflow, return MAX_INT.

看讨论区大神的思路:

In this problem, we are asked to divide two integers. However, we are not allowed to use division, multiplication and mod operations. So, what else can we use? Yeah, bit manipulations.

Let‘s do an example and see how bit manipulations work.

Suppose we want to divide 15 by 3, so 15 is dividend and 3 is divisor. Well, division simply requires us to find how many times we can subtract the divisor from the the dividend without making the dividend negative.

Let‘s get started. We subtract 3 from 15 and we get 12, which is positive. Let‘s try to subtract more. Well, we shift 3 to the left by 1 bit and we get 6. Subtracting 6 from 15 still gives a positive result. Well, we shift again and get 12. We subtract 12 from 15 and it is still positive. We shift again, obtaining 24 and we know we can at most subtract 12. Well, since 12 is obtained by shifting 3 to left twice, we know it is 4 times of 3. How do we obtain this 4? Well, we start from 1 and shift it to left twice at the same time. We add 4 to an answer (initialized to be0). In fact, the above process is like 15 = 3 * 4 + 3. We now get part of the quotient (4), with a remainder 3.

Then we repeat the above process again. We subtract divisor = 3 from the remaining dividend = 3 and obtain 0. We know we are done. No shift happens, so we simply add 1 << 0 to the answer.

Now we have the full algorithm to perform division.

According to the problem statement, we need to handle some exceptions, such as overflow.

Well, two cases may cause overflow:

  1. divisor = 0;
  2. dividend = INT_MIN and divisor = -1 (because abs(INT_MIN) = INT_MAX + 1).

Of course, we also need to take the sign into considerations, which is relatively easy.

Putting all these together, we have the following code.

class Solution {
public:
    int divide(int dividend, int divisor) {
        if (!divisor || (dividend == INT_MIN && divisor == -1))
            return INT_MAX;
        int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
        long long dvd = labs(dividend);
        long long dvs = labs(divisor);
        int res = 0;
        while (dvd >= dvs) {
            long long temp = dvs, multiple = 1;
            while (dvd >= (temp << 1)) {
                temp <<= 1;
                multiple <<= 1;
            }
            dvd -= temp;
            res += multiple;
        }
        return sign == 1 ? res : -res;
    }
};
 1 #include<iostream>
 2 #include<limits>
 3 using namespace std;
 5 class Solution {
 6 public:
 7     int divide(int dividend, int divisor)
 8     {
 9         int sign = ((dividend > 0) ^ (divisor > 0) ? -1 : 1);
10         if (!divisor || (dividend==INT_MIN&&divisor==-1))
11             return INT_MAX;
12         long long divid = labs(dividend), divis = labs(divisor);
13         long long  res = 0;
14         while (divid >= divis)
15         {
16             long long temp = divis,multi_time=1;
17             while (divid >= (temp<<1))
18             {
19                 temp <<= 1;
20                 multi_time <<=1;
21             }
22             divid -= temp;
23             res += multi_time;
24         }
25         return sign == 1 ? res:-res;
26     }
27 };
28 int main()
29 {
30     Solution test;
31     int res = test.divide(0, 1);
32     cout << res << endl;
33     return 0;
34 }
时间: 2024-10-05 04:44:58

Divide Two Integers leetcode的相关文章

Divide Two Integers —— LeetCode

Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. 题目大意:不用乘除取模运算计算两个数的除. 解题思路:只能用位运算了,当被除数大于除数,除数左移1位.2位……直到得到最大的然后用被除数减去它,将因数加到res上,这里有点二分的意思,依次循环往复,这里我把两个数都设为负数,因为0x80000000是最小的负数,它没有对应的最

Divide Two Integers leetcode java

题目: Divide two integers without using multiplication, division and mod operator. 题解: 这道题我自己没想出来...乘除取模都不让用..那只有加减了...我参考的http://blog.csdn.net/perfect8886/article/details/23040143 代码如下: 1      public int divide(int dividend, int divisor) {   2        

LeetCode --- 29. Divide Two Integers

题目链接:Divide Two Integers Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. 这道题的要求是在不使用乘法.除法.取模运算的前提下实现两个整数相除.如果溢出,返回MAX_INT. 这道题的直接思路是用被除数不断减去除数,直到为0.这种方法的迭代次数是结果的大小,即比如结果为n,算法复杂度是O(n). 可以

[Leetcode][Python]29: Divide Two Integers

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 29: Divide Two Integershttps://oj.leetcode.com/problems/divide-two-integers/ Divide two integers without using multiplication, division and mod operator.If it is overflow, return MAX_INT. ===C

LeetCode 28 Divide Two Integers

Divide two integers without using multiplication, division and mod operator. 思路:1.先将被除数和除数转化为long的非负数,注意一定要为long,因为Integer.MIN_VALUE的绝对值超出了Integer的范围. 2.常理:任何正整数num都可以表示为num=2^a+2^b+2^c+...+2^n,故可以采用2^a+2^b+2^c+...+2^n来表示商,即dividend=divisor*(2^a+2^b+

LeetCode: Divide Two Integers [028]

[题目] Divide two integers without using multiplication, division and mod operator. [题意] 计算两个数的商,不能使用乘.除.取余操作 [思路] 用加法,确定多少除数相加其和恰好<=被除数 为了提高算法效率,利用贪心思想,采用滚雪球式的翻倍叠加策略,使和快速逼近被除数 几种特殊情况需要注意: 1. 结果是负数 2. 除数的绝对值要比被除数的绝对值大 3. 除数是0 4. 被除是0 5. 注意除数翻倍累加时越界,超过i

[LeetCode] 数学计算模拟类问题:除法和幂,注意越界问题。题 Pow(x, n) ,Divide Two Integers

引言 数学计算的模拟类题目,往往是要求实现某种计算(比如两数相除),实现的过程中会有所限定,比如不允许乘法等等. 这类题目首先要注意计算过程中本身的特殊情况.比如求相除,则必须首先反映过来除数不能为0. 其次要记得考虑负数的情况,如果计算范围不单单是整数,还要考虑double的比较方式. 最后要注意越界情况,这个是最容易犯错的,只能具体问题具体分析. 例题 1 Pow(x, n) Implement pow(x, n). class Solution { public: double pow(d

leetcode——Divide Two Integers 不用乘除取余操作求除法(AC)

Divide two integers without using multiplication, division and mod operator. 题目只有简单的一句话,看起来可真简单啊,呵呵,假象.这个题目的难点在于对时间效率的限制和边界值的测试.第一印象肯定是循环一个个把因子从被除数中减去不久行了么,可是对于比如INT_MAX/1或者INT_MIN/1之类的执行时间长的可怕,会超出时间限制.改善时间效率的思路是参考网上别人代码,将因子不断乘以2(可以通过移位实现,同时结果也从1开始不断

【leetcode刷题笔记】Divide Two Integers

Divide two integers without using multiplication, division and mod operator. 题解:要求不用乘除和取模运算实现两个数的除法. 那么用加减法是很自然的选择.不过如果一次只从被除数中剪掉一个除数会TLE.所以我们借助移位运算,依次从被除数中减去1个除数,2个除数,4个除数......当减不动的时候,再依次从被除数中减去......4个除数,2个除数,1个除数. 例如50除以5的计算过程如下: dividend exp tem