程序员面试金典 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;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值