程序员面试金典 8.5

Recursive Multiply:实现一个递归算法,只使用加法、减法和移位实现两个数字相乘。

可以将其中的一个数减半,求出乘积。如果被减半的数是偶数,则将乘积翻倍即可,否则再计算另一部分的乘积。

class Solution {
public:
    int multiply(int A, int B) {
        int smaller = A <= B ? A : B;
        int bigger = A <= B ? B : A;
        return calProduct(smaller, bigger);
    }
private:
    int calProduct(const int smaller, const int bigger)
    {
        if(smaller == 1) return bigger;
        int half = smaller >> 1;
        int side = calProduct(half, bigger);
        if(smaller & 0x1 == 1)
            return side + calProduct(smaller - half, bigger);
        else
            return side << 1;
    }
};

注意当被减半的数是奇数时,会发生重复计算,例如对于9,减半之后分为45,进而又被减半为223,所以可以通过记忆化搜索,将结果保存下来。

class Solution {
public:
    int multiply(int A, int B) {
        int smaller = A <= B ? A : B;
        int bigger = A <= B ? B : A;
        Memo.assign(smaller + 1, 0);
        Memo[1] = bigger;
        return calProduct(smaller, bigger);
    }
private:
    vector<int> Memo;
    int calProduct(const int smaller, const int bigger)
    {
        if(Memo[smaller] != 0) return Memo[smaller];
        int half = smaller >> 1;
        int side1 = calProduct(half, bigger);
        int side2 = side1;
        if(smaller & 0x1 == 1)
            side2 = calProduct(smaller - half, bigger);
        Memo[smaller] = side1 + side2;
        return Memo[smaller];
    }
};

上面的两种方法在smaller是偶数时会快一些,而奇数则会慢一些,因为奇数需要再次调用calProduct(),为了解决这个问题,在奇数时依然可以采用和偶数相同的计算方法,最后再单独补充一个bigger即可,这时算法才真正变成了O(logsmaller)

class Solution {
public:
    int multiply(int A, int B) {
        int smaller = A <= B ? A : B;
        int bigger = A <= B ? B : A;
        return calProduct(smaller, bigger);
    }
private:
    int calProduct(const int smaller, const int bigger)
    {
        if(smaller == 1) return bigger;
        int half = smaller >> 1;
        int side = calProduct(half, bigger);
        if(smaller & 0x1 == 1)
            return (side << 1) + bigger;
        else
            return side << 1;
    }
};
发布了194 篇原创文章 · 获赞 2 · 访问量 7717

猜你喜欢

转载自blog.csdn.net/RayoNicks/article/details/105453040