两个任意长度的长整数相乘(华为oj,C++)

来源:互联网 发布:淘宝onlyanna真名晓颖 编辑:程序博客网 时间:2024/05/17 23:34
<pre name="code" class="cpp">#include "oj.h"#include<iostream>int main(void){string strMultiplierA = "9999";string strMultiplierB = "9999";string strRst = "\0";multiply (strMultiplierA,strMultiplierB,strRst);cout << strRst;return 0;}/*****************************************************************************Prototype    : multiplyDescription  : 两个任意长度的长整数相乘, 输出结果Input pAram  : const std::string strMultiplierA  乘数Aconst std::string strMultiplierB  乘数BOutput       : std::string strRst            乘法结果Return Value : int                       0  正确  -1  异常*****************************************************************************/int multiply (const std::string strMultiplierA,const std::string strMultiplierB, std::string &strRst) {/* 在这里实现功能 */string chengshuA = strMultiplierA;string chengshuB = strMultiplierB;int a = chengshuA.length();int b = chengshuB.length();int strRst_length = 0;int c = (a+1)*(b+1);int *p = new int[c];//逆序存放的结果int *pA = new int[a];//逆序存放的乘数Aint *pB = new int[b];//逆序存放的乘数B//测试是否有乘数为空if ((a == 0) || (b == 0))return -1;for (int i = 0; i != c; i++)p[i] = 0;//把乘数逆序放到数组pA中,若chengshuA是12345,则pA是54321for (string::size_type index = 0; index !=  chengshuA.length(); index++) pA[a-1-index] = chengshuA.at(index) - '0';//pA[(a-1) - index]for (string::size_type index = 0; index != chengshuB.length(); index++)pB[b-1-index] = chengshuB.at(index) - '0';for (int temp_b = 0; temp_b != b; temp_b++)  //每个位循环相乘{for (int temp_a = 0; temp_a != a; temp_a++)//pA的每个位循环与pB[temp_b]相乘{//p[temp_a+temp_b]利用temp_b起到移位的作用,如temp_b是十位数,则在乘法计算中要向后移动移位。int temp = p[temp_a+temp_b] + pA[temp_a]*pB[temp_b];p[temp_a+temp_b] = temp % 10;int carry = temp/10; //进位int x = temp_a + temp_b +1;//c = (a+1)*(b+1),足够大;大数相加与数相乘同时计算,进位有可能是多位数while(carry != 0)//进位不等于0{p[x] = p[x] + carry%10;//若前面有进位,则提前把进位加到求和结果p[x]上carry = carry/10;x++;}}}while (c-- > 0)  //判断结果有几位{if (p[c] != 0){strRst_length = c + 1;break;}}char ch;for (int i = strRst_length - 1; i >= 0 ; i--)  //把结果放入字符串中{ch = p[i] + '0';strRst.push_back(ch);}if (strRst.empty())//如果结果为0,则输出字符串为“0”{strRst = "0";}return 0;}


                                             
0 0
原创粉丝点击