标签:
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.
class Solution { public: string multiply(string num1, string num2) { string addDeci(string a,string b); string str;//默认为空串 //存储最后结果 string strBit;//存储一位相乘的结果. if (num2.size()>num1.size()) { string tmp=num1; num1=num2; num2=tmp; } if (num2=="0") { return "0"; } int lengthA=num1.size(); int lengthB=num2.size(); //小的 int carry =0; //进位标志 char bitSum; int MultiplySum;//每一次乘数个位的乘 for(int j=0;j<lengthB;j++)//j个相加..1,10,100 { strBit=""; for(int i=0;i<lengthA;i++) //每一位和他相加.. { MultiplySum=(num2[lengthB-j-1]-'0')*(num1[lengthA-i-1]-'0')+carry; carry=MultiplySum/10; if(carry>0) //有进位 { MultiplySum=MultiplySum%10; bitSum='0'+MultiplySum; strBit=bitSum+strBit; //每一次一个右边最小加入进来.. } else { bitSum='0'+MultiplySum; strBit=bitSum+strBit; } } if(carry>0) { MultiplySum=carry; bitSum='0'+MultiplySum; //char型 strBit=bitSum+strBit; } carry=0; //加一位,10,20,两个数相加.. for (int Cntdigit=0;Cntdigit<j;Cntdigit++)//看移动多少位 { strBit=strBit+"0"; } str=addDeci(strBit,str); } return str; } }; string addDeci(string a,string b) { string str;//默认为空串 if (b.size()>a.size()) { string tmp=b; b=a; a=tmp; } int lengthA=a.size(); int lengthB=b.size(); //最后一位与最后一位相加.. int i=lengthA-1; int j=lengthB-1; int carry=0; int bit_Sum=0; char bitCurrent; while (j>=0) //先加最低位 { bit_Sum=(a[i]-'0'+b[j]-'0')+carry; //计算每一位增加的数字 if (bit_Sum/10>=1) //1+1//有进位,自己变为2的余数 { //之间记录到a[i]里面 carry=bit_Sum/10; //进位 bitCurrent=('0'+bit_Sum%10); str=bitCurrent+str; } else { carry=0; bitCurrent=('0'+bit_Sum); //convert to char str=bitCurrent+str; } i--; j--; } while (i>=0) { bit_Sum=(a[i]-'0')+carry; if (bit_Sum/10>=1) //1+1 { //之间记录到a[i]里面 carry=bit_Sum/10; //进位 bitCurrent=('0'+bit_Sum%10); //1+1=2,+1=3 str=bitCurrent+str; } else { carry=0; //没有进位 bitCurrent=('0'+bit_Sum); str=bitCurrent+str; } i--; } if (carry>0) { bitCurrent=('0'+carry); str=bitCurrent+str; return str; } return str; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/q286989429/article/details/47017641