Divide Two Integers题解以及类似题目的总结

来源:互联网 发布:桌面美化软件 编辑:程序博客网 时间:2024/06/03 23:25
  

29. Divide Two Integers

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

If it is overflow, return MAX_INT.

思路很简单,既然不能用乘除法,自然是用加减法了来代替。

瓶颈也很显而易见,按线性加减发会超时。

这个题目有两个思路,先说第一个。

假设现在我们是算x / y,那么考虑x > 2^n * y,求出这个最大的2^n,然后将x减去2^n * y,然后继续求新的2^n,直到x<y,最后将历次2^n加起来就是答案了。有没有种二进制的意思。

public class Solution {    public int divide(int dividend, int divisor) {    long result = 0;    int flag = 1;    if (dividend < 0)    flag = -flag;    if (divisor < 0)    flag = -flag;        long x = Math.abs((long)dividend);    long y = Math.abs((long)divisor);        while (x>=y) {    long temp = y;    long c = 1;    while (temp <= x) {    temp <<= 1;    c <<= 1;    }    result += (c>>1);    x -= (temp>>1);    }    if (result*(long)flag > Integer.MAX_VALUE || result*(long)flag < Integer.MIN_VALUE)    return Integer.MAX_VALUE;    else    return (int)(result*(long)flag);      }}

第二个思路很简单,就是预处理,比如我们还是算x / y,我们怕的不就是当出现2000000000 / 1这种情况出现时会超时吗,那我们先预处理y的倍数,我先用加法把y的100000倍预先算出来,存位m,然后用x一次次去减m就行了,当最后x < m的时候,再对剩下的x作 x / y,结果就是剩下的x /y + 100000*m。



用这个方法来个实战。

50. Pow(x, n)

Implement pow(xn).

class Solution {public:    double myPow(double x, int n) {        double result = 1;        if (n >= 0)        {            double temp = 1;            for (int i=0; i<10000; i++)                temp *= x;            while (n-10000 > 0)            {                result *= temp;                n -= 10000;            }            for (int i=0; i<n; i++)                result *= x;            return result;        }        else        {            long m = n;            m = -m;                        double temp = 1;            for (int i=0; i<10000; i++)                temp *= x;            while (m-10000 > 0)            {                result *= temp;                m -= 10000;            }            for (int i=0; i<m; i++)                result *= x;            return 1/result;        }    }};


看一下复杂度,应该是第一种方法更优一点,毕竟是log级别的。

本菜正在刷LeetCode,写过的代码都放到了https://github.com/lcxywfe/LeetCode,欢迎各犇交流~

0 0
原创粉丝点击