首页 > 代码库 > [LeetCode]43.Multiply Strings
[LeetCode]43.Multiply Strings
【题目】
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.
【分析】
高精度乘法(大数乘法)
【代码】
/********************************* * 日期:2015-01-28 * 作者:SJF0115 * 题目: 43.Multiply Strings * 网址:https://oj.leetcode.com/problems/multiply-strings/ * 结果:AC * 来源:LeetCode * 博客: **********************************/ #include <iostream> #include <cstring> using namespace std; class Solution { public: string multiply(string num1, string num2) { int len1 = num1.length(); int len2 = num2.length(); // 容错处理 if(len1 <= 0 || len2 <= 0){ return ""; }//if int sum = 0; int len3 = len1 + len2; char result[len3]; memset(result,'0',sizeof(result[0])*(len3+1)); for(int i = len1 - 1,m = 0;i >= 0;--i,++m){ for(int j = len2 - 1,n = 0;j >= 0;--j,++n){ sum = (num1[i] - '0') * (num2[j] - '0') + result[m+n] - '0'; result[m+n] = sum % 10 + '0'; // 进位 result[m+n+1] += sum / 10; }//for }//for //确定乘积的位数 while(result[len3] == '0' && len3 > 0){ --len3; }//while //注意:加'\0' result[len3+1] = '\0'; //翻转 int temp; for(int i = 0,j = len3;i < j;++i,--j){ temp = result[i]; result[i] = result[j]; result[j] = temp; }//for return string(result); } }; int main(){ Solution solution; string num1("0"); string num2("123"); string result = solution.multiply(num1,num2); // 输出 cout<<result<<endl; return 0; } /*for(int i = 0;i < result.size();++i){ for(int j = 0;j < result[i].size();++j){ cout<<result[i][j]<<" "; } cout<<endl; }*/
[LeetCode]43.Multiply Strings
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。