537. Complex Number Multiplication

题目描述:

Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i2 = -1 according to the definition.

Example 1:

Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.

 

Example 2:

Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.

 

Note:

  1. The input strings will not have extra blank.
  2. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.

解题思路:

题目本质很简单,解析输入参数稍微繁琐点。

代码:

复制代码
 1 class Solution {
 2 public:
 3     string complexNumberMultiply(string a, string b) {
 4         int num1, num2, num3, num4;
 5         int res1, res2;
 6         string sig1, sig2, res;
 7         parse(num1, num2, sig1, a);
 8         parse(num3, num4, sig2, b);
 9         res1 = num1 * num3 - num2 * num4;
10         res2 = num1 * num4 + num2 * num3;
11         res = to_string(res1) + "+" +to_string(res2) + "i";
12         return res;
13     }
14     void parse(int& a, int& b, string& sig, const string& input) {
15         size_t plus =  input.find("+");
16         size_t i = input.find("i");
17         size_t minus = input.find("-");
18         a = stoi(input.substr(0, plus));
19         if (minus != string::npos) {
20             b = stoi(input.substr(plus+1, i-(plus+1)));
21             sig = "-";
22         } else {
23             b = stoi(input.substr(plus+1, i-(plus+1)));
24             sig = "+";
25         }
26     }
27 };
复制代码

 

posted @   gszzsg  阅读(94)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
阅读排行:
· 【译】我们最喜欢的2024年的 Visual Studio 新功能
· 个人数据保全计划:从印象笔记迁移到joplin
· Vue3.5常用特性整理
· 重拾 SSH:从基础到安全加固
· 为什么UNIX使用init进程启动其他进程?
点击右上角即可分享
微信分享提示