递归乘法。 写一个递归函数,不使用 * 运算符, 实现两个正整数的相乘。可以使用加号、减号、位移,但要吝啬一些。
示例1:
输入:A = 1, B = 10
输出:10
示例2:
输入:A = 3, B = 4
输出:12
提示:
保证乘法范围不会溢出
code1:乘法看做加法
class Solution { public: int multiply(int A, int B) { if(A == 0 || B == 0){ return 0; } else if(A == 1 || B == 1){ return A == 1 ? B : A; } int res = multiply(A, B-1) + A; return res; } };
code2:乘法看做位移运算;如12*6=12*(4+2),也就是把乘数拆成2的整数次幂即可。迭代
class Solution { public: int multiply(int A, int B) { if(A == 0 || B == 0){ return 0; } else if(A == 1 || B == 1){ return A == 1 ? B : A; } int bigger = max(A, B); int little = min(A, B); int res = 0; for(int i = 0; little; ++i){ if(little & 1) res += bigger << i; little >>= 1; } return res; } };
递归
class Solution { private: void multiplyCore(int bigger, int little, int &res, int i){ if((little >> i) == 0) return ; if((little >> i) & 1) res += bigger << i; multiplyCore(bigger, little, res, i+1); } public: int multiply(int A, int B) { if(A == 0 || B == 0) return 0; else if(A == 1 || B == 1) return A == 1 ? B : A; int bigger = max(A, B); int little = min(A, B); int res = 0; multiplyCore(bigger, little, res, 0); return res; } };