problem:
thinking:
(1)用字符串表示大数相乘,可以不用考虑溢出的问题
(2)第一种方法比较笨重,直接模拟乘法(我在自己机器上测试没问题,提交时显示runtime error,郁闷)
class Solution { public: string multiply(string num1,string num2) { vector<string> container; string ret; int length1=num1.size(); int length2=num2.size(); if(length2>length1) { string tmp=num1; num1=num2; num2=tmp; } int i=0; int index=length2-1; while(index>=0) { string res=string_multiply_char(num1,num2.at(index),i); container.push_back(res); index-- ; i++; } ret=string_add_atring(container); return ret; } protected: string string_multiply_char(string str,char ch,int i) { cout<<str<<" * "<<ch<<" i "<<i<<endl; string ret; string tail; for(int j=0;j<i;j++) tail.push_back('0'); int a=0;//jin wei int y=ch-'0'; int count = str.size()-1; stack<char> _stack; while(count>=0) { int x=str.at(count)-'0'; cout<<"char x: "<<x<<endl; int mid = x*y; char z = (mid+a)%10+'0'; a=(mid+a)/10; _stack.push(z); count--; } if(a>0) _stack.push(a+'0'); while(!_stack.empty()) { ret.push_back(_stack.top()); _stack.pop(); } ret+=tail; cout<<" ret "<<ret<<endl; return ret; } string string_add_atring(vector<string> res) { string str1; string str2; if(res.size()<2) return str1; str1=res[0]; for(int i=1;i<res.size();i++) { str2=res[i]; cout<<str1<<"+"<<str2<<endl; int m=str1.size(); int n=str2.size(); int count = min(m,n); int a=0; stack<char> _stack; for(int j=0;j<count;j++) { int x=str1.at(m-j-1)-'0'; int y=str2.at(n-j-1)-'0'; char mid=(x+y+a)%10+'0'; cout<<"char mid"<<mid<<endl; a =(x+y+a)/10; cout<<"jin wei "<<a<<endl; _stack.push(mid); } if(m>n) { for(int k=m-n-1;k>=0;k--) { char mid1=a+str1.at(k); cout<<" mid1 "<<mid1<<endl; _stack.push(mid1); a=0; } } else if(m<n) { for(int l=n-m-1;l>=0;l--) { char mid2=a+str2.at(l); cout<<"mid2 "<<mid2<<endl; _stack.push(mid2); a=0; } } else { if(a>0) _stack.push(a+'0'); } str1.clear(); while(!_stack.empty()) { str1.push_back(_stack.top()); _stack.pop(); } }//for return str1; } };
方法二:比较简洁
class Solution { public: string multiply(string num1,string num2) { reverse(num1.begin(),num1.end()); reverse(num2.begin(),num2.end()); if (("0" == num1) || ("0" == num2)) { return "0"; } string result = ""; int i,j; int flag = 0,steps = 0; for (int i = 0; i < num1.length(); ++i) { int position = steps; for (int j = 0; j < num2.length(); ++j) { int v = (num1[i] - '0') * (num2[j] - '0') + flag; if (position < result.length()) { v += result[position] - '0'; result[position] = (v % 10) + '0'; } else { result.append(1,(v % 10) + '0'); } flag = v / 10; ++position; } if (flag > 0) { result.append(1,flag + '0'); } flag = 0; ++steps; } reverse(result.begin(),result.end()); return result; } };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。