字符串相加:
字符串相乘:
基础知识:
- push_back是编程语言里面的一个函数名。如c++中的vector头文件里面就有这个push_back函数,在vector类中作用为在vector尾部加入一个数据。string中也有这个函数,作用是字符串之后插入一个字符。
- reverse函数的用法:
头文件:#include <algorithm>
这个函数用于反转 [first,last) 之间的内容 ,这个函数是没有返回值的。
使用实例:- 反转vector容器中元素顺序:
reverse(v.begin( ),v.end( ));
- 反转string类:
reverse(str.begin(),str.end());
- 反转vector容器中元素顺序:
这个反转是包含First所指的数据,不包含last所指的数据的。
解题:
字符串相加
模拟竖式运算:
class Solution {
public:
string addStrings(string num1, string num2) {
int i = num1.length()-1;
int j = num2.length()-1;
int add = 0;
string res = "";
while (i >= 0 || j >= 0 || add != 0){
int x = i >= 0 ? num1[i] - '0' : 0;
int y = j >= 0 ? num2[j] - '0' : 0;
int result = x+y+add;
add = result/10;
res.push_back('0' + result%10); //这里是在字符串后增添元素
i-=1;
j-=1;
}
reverse(res.begin(),res.end()); //将字符串反转
return res;
}
};
当i或者j<0时,说明其对应的位置已经空了,要进行补0操作。
字符串相乘
这个方法提交的时候,提示执行出错,问题是越界,但是我不知道问题出在哪。
class Solution {
public:
string multiply(string num1, string num2) {
if(num1=="0" || num2=="0")
return "0";
string product="";
int i = num1.length()-1;
int j = num2.length()-1;
string curr,res;
while(j>=0){
// if (num2[j] == '0'){
// j--;
// continue;
//
// }
int x = num2[j] - '0';
int count = num2.length()-j-1;
while(count!=0){
curr.push_back('0');
count--;
}
int add = 0;
for(;i>=0 || add>0 ; i--){
int y = num1[i] - '0';
int result = i>=0 ? x * y + add : add ;
curr.push_back('0'+result%10);
add = result / 10;
}
i = num1.length()-1;
reverse(curr.begin(),curr.end());
cout<<curr<<endl;
product = addStrings(curr,product);
curr.clear(); //very important 之前就因为没有清除这里的数据屡屡出错
j--;
}
cout<<product<<endl;
return product;
}
string addStrings(string num1, string num2) {
int i = num1.length()-1;
int j = num2.length()-1;
int add = 0;
string res = "";
while (i >= 0 || j >= 0 || add != 0){
int x = i >= 0 ? num1.at(i) - '0' : 0;
int y = j >= 0 ? num2.at(j)- '0' : 0;
int result = x+y+add;
add = result/10;
res.push_back('0' + result%10);
i-=1;
j-=1;
}
reverse(res.begin(),res.end());
return res;
}
};
还有一种更方便的方法是用数组代替字符串存储结果,两个乘数的长度分别为M、N,乘积的长度会是M+N+1或者M+N。这种做法省去了字符串相加的步骤。
时间复杂度为O(MN),空间复杂度为数组长度,O(M+N)。