思想:每次取第二个数的最高位进行一次乘法,把结果乘以10和下一次结果相加,题目来源:leetcode
class Solution { public: //一个整数乘以一个个位数 string multOneBit(string num,int data) { int i = num.size() - 1,carry = 0; string res; for(;i >= 0;--i) { int value = (num[i] - '0') * data + carry; carry = value / 10; value = value % 10; res += (value + '0'); } if(carry > 0)res += (carry +'0'); reverse(res.begin(),res.end()); return res; } //两个大整数的加法 string add(string s1,string s2) { string res; int i = s1.size() - 1,j = s2.size() - 1,carry = 0; while(i >= 0 && j >= 0) { int value = s1[i--] + s2[j--] - '0' - '0' + carry; carry = value / 10; value = value % 10; res += value + '0'; } while(i >= 0) { int value = s1[i--] - '0' + carry; carry = value / 10; value = value % 10; res += value + '0'; } while(j >= 0) { int value = s2[j--] - '0' + carry; carry = carry / 10; value = value % 10; res += value + '0'; } if(carry > 0)res += (carry + '0'); reverse(res.begin(),res.end()); return res; } string multiply(string num1, string num2) { int length2 = num2.size(),i; string res; for(i = 0;i < length2;++i) { string s = multOneBit(num1,num2[i] - '0');//每次取第二个数的最高位进行乘法算法 if(res.size() != 0) { res = add(res+'0',s);//把原来的结果扩大10倍加上当前的结果 } else res = s; } if(res[0] == '0')res = '0'; return res; } };
原文地址:http://blog.csdn.net/fangjian1204/article/details/38496931