LeetCode 题解工作台
复数乘法
复数 可以用字符串表示,遵循 " 实部 + 虚部 i" 的形式,并满足下述条件: 实部 是一个整数,取值范围是 [-100, 100] 虚部 也是一个整数,取值范围是 [-100, 100] i 2 == -1 给你两个字符串表示的复数 num1 和 num2 ,请你遵循复数表示形式,返回表示它们乘…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数学·string
答案摘要
我们可以将复数字符串转换成对应的实部 和虚部 ,然后根据复数乘法的公式 $(a_1 + b_1i) \times (a_2 + b_2i) = (a_1a_2 - b_1b_2) + (a_1b_2 + a_2b_1)i$ 计算出结果。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
复数 可以用字符串表示,遵循 "实部+虚部i" 的形式,并满足下述条件:
实部是一个整数,取值范围是[-100, 100]虚部也是一个整数,取值范围是[-100, 100]i2 == -1
给你两个字符串表示的复数 num1 和 num2 ,请你遵循复数表示形式,返回表示它们乘积的字符串。
示例 1:
输入:num1 = "1+1i", num2 = "1+1i" 输出:"0+2i" 解释:(1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i ,你需要将它转换为 0+2i 的形式。
示例 2:
输入:num1 = "1+-1i", num2 = "1+-1i" 输出:"0+-2i" 解释:(1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i ,你需要将它转换为 0+-2i 的形式。
提示:
num1和num2都是有效的复数表示。
解题思路
方法一:模拟
我们可以将复数字符串转换成对应的实部 和虚部 ,然后根据复数乘法的公式 计算出结果。
时间复杂度 ,空间复杂度 。
class Solution:
def complexNumberMultiply(self, num1: str, num2: str) -> str:
a1, b1 = map(int, num1[:-1].split("+"))
a2, b2 = map(int, num2[:-1].split("+"))
return f"{a1 * a2 - b1 * b2}+{a1 * b2 + a2 * b1}i"
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Evaluates the candidate's ability to handle string manipulation effectively.
- question_mark
Tests understanding of complex number arithmetic and correct use of the multiplication formula.
- question_mark
Examines the candidate's ability to reformat a result based on specific requirements.
常见陷阱
外企场景- error
Forgetting to correctly parse the input strings, especially when the signs are negative.
- error
Incorrectly formatting the result when the imaginary part is negative, leading to a malformed output.
- error
Misunderstanding the complex number multiplication formula, especially when handling the imaginary component.
进阶变体
外企场景- arrow_right_alt
Implementing the solution with a different method of extracting the real and imaginary parts, such as using regular expressions.
- arrow_right_alt
Handling edge cases where the real or imaginary parts are zero.
- arrow_right_alt
Optimizing the solution for different input formats or handling inputs with larger sizes.