題目來(lái)源
求字符串復(fù)數(shù)的乘法操作僻族。主要是考慮string的一些操作粘驰,我想了想,先找出“+”在哪里述么,然后分割實(shí)部和虛部蝌数,然后進(jìn)行計(jì)算,用了stringstream度秘。代碼如下:
class Solution {
public:
string complexNumberMultiply(string a, string b) {
int n1 = a.size(), n2 = b.size();
string realA, realB, imageA, imageB;
for (int i=0; i<n1; i++) {
if (a[i] == '+') {
realA = a.substr(0, i);
imageA = a.substr(i+1, n1-i-2);
}
}
for (int i=0; i<n2; i++) {
if (b[i] == '+') {
realB = b.substr(0, i);
imageB = b.substr(i+1, n2-i-2);
}
}
int irealA, irealB, iimageA, iimageB;
istringstream (realA) >> irealA;
istringstream (realB) >> irealB;
istringstream (imageA) >> iimageA;
istringstream (imageB) >> iimageB;
return to_string(irealA * irealB - iimageA * iimageB) + "+" + to_string(irealA * iimageB + irealB * iimageA) + "i";
}
};
然后發(fā)現(xiàn)自己還是太弱了籽前,streamstring不會(huì)用。
看了下討論區(qū)敷钾,代碼如下:
class Solution {
public:
string complexNumberMultiply(string a, string b) {
int ra, ia, rb, ib;
char buff;
stringstream aa(a), bb(b), ans;
aa >> ra >> buff >> ia >> buff;
bb >> rb >> buff >> ib >> buff;
ans << ra*rb - ia*ib << "+" << ra*ib + rb*ia << "i";
return ans.str();
}
};