|
| 1 | +// Runtime: 0 ms (Top 100.0%) | Memory: 6.40 MB (Top 16.79%) |
| 2 | + |
1 | 3 | class Solution {
|
2 |
| -public: |
3 |
| - pair<int,int> seprateRealAndImg(string &s){ |
4 |
| - int i = 0; |
5 |
| - string real,img; |
6 |
| - while(s[i] != '+') real += s[i++]; |
7 |
| - while(s[++i] != 'i') img += s[i]; |
8 |
| - |
9 |
| - return {stoi(real),stoi(img)}; |
| 4 | +public: |
| 5 | + pair<int, int> parse(string num) { |
| 6 | + int i = num.find('+'); |
| 7 | + double real = stoi(num.substr(0, i)); |
| 8 | + double imaginary = stoi(num.substr(i+1, num.size()-i-2)); |
| 9 | + pair<int, int> res(real, imaginary); |
| 10 | + return res; |
10 | 11 | }
|
| 12 | + |
11 | 13 | string complexNumberMultiply(string num1, string num2) {
|
12 |
| - pair<int,int> x = seprateRealAndImg(num1); |
13 |
| - pair<int,int> y = seprateRealAndImg(num2); |
14 |
| - |
15 |
| - int a1 = x.first,b1 = x.second; |
16 |
| - int a2 = y.first,b2 = y.second; |
17 |
| - |
18 |
| - int real = (a1 * a2) - (b1*b2); |
19 |
| - int img = (b1*a2) + (a1 * b2); |
| 14 | + pair<int, int> a = parse(num1), b = parse(num2); |
| 15 | + int real_a = a.first, imag_a = a.second; |
| 16 | + int real_b = b.first, imag_b = b.second; |
20 | 17 |
|
21 |
| - return to_string(real) + "+" + to_string(img) + "i"; |
| 18 | + return to_string(real_a * real_b - imag_a * imag_b) + '+' + to_string(real_a * imag_b + real_b * imag_a)+'i' ; |
22 | 19 | }
|
23 | 20 | };
|
0 commit comments