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:
- The input strings will not have extra blank.
- 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 };
分类:
LeetCode刷题
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 【译】我们最喜欢的2024年的 Visual Studio 新功能
· 个人数据保全计划:从印象笔记迁移到joplin
· Vue3.5常用特性整理
· 重拾 SSH:从基础到安全加固
· 为什么UNIX使用init进程启动其他进程?