537. Complex Number Multiplication-Medium

来源:互联网 发布:日式装修风格知乎 编辑:程序博客网 时间:2024/06/08 03:23

大水题!leetcode大概是看答案代码行数判断难易程度的吧。
写一道Medium动态规划写到心态崩了,所以今天先水一道,下周再填那个坑。

Description

给定两个用string表示的复数输出乘积。
Example:
Input: “1+1i”, “1+1i”
Output: “0+2i”

Code

#include <cstdlib>#include <sstream>class Solution {public:    string complexNumberMultiply(string a, string b) {        pair<int, int> trsA = transform(a);        pair<int, int> trsB = transform(b);        int real = trsA.first*trsB.first - trsA.second*trsB.second;        int imaginary = trsA.second*trsB.first + trsA.first*trsB.second;        string ret;        stringstream ss;        ss << real << "+" << imaginary << "i";        ss >> ret;        return ret;    }    pair<int, int> transform(string a) {        size_t plus_pos = a.find('+');        int real = atoi(a.substr(0, plus_pos).c_str());        int imaginary = atoi(a.substr(plus_pos+1, a.size()-plus_pos-2).c_str());        pair<int, int> ret(real, imaginary);        return ret;    }};

Summary

1.string转int:用cstdlib中的atoi(string.c_str())
2.int转string:用sstream中的stringstream,造一个这种流对象,往对象中输入int,输出到目标string。同时可用该对象做拼接。
3.size_t也不过就是unsigned int,要加要减随便当int用。

下面照例放上“别人家的代码”:
stringstream玩得好

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();}
原创粉丝点击