标签:
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
Subscribe to see which companies asked this question
ACM竞赛常考的大数相乘算法,利用字符串来表示大数字进行计算。
string multiply(string num1, string num2) { string num(num1.size() + num2.size(), ‘0‘); for (int i = num1.size() - 1; i >= 0; --i) { int carry = 0; for (int j = num2.size() - 1; j >= 0; --j) { int tmp = num[i + j + 1] - ‘0‘ + (num1[i] - ‘0‘) * (num2[j] - ‘0‘) + carry; num[i + j + 1] = tmp % 10 + ‘0‘; carry = tmp / 10; } num[i] += carry; } size_t startpos = num.find_first_not_of(‘0‘); if (startpos != string::npos) return num.substr(startpos); return "0"; }
标签:
原文地址:http://www.cnblogs.com/sdlwlxf/p/5122584.html