LeetCode 题解工作台

复数乘法

复数 可以用字符串表示,遵循 " 实部 + 虚部 i" 的形式,并满足下述条件: 实部 是一个整数,取值范围是 [-100, 100] 虚部 也是一个整数,取值范围是 [-100, 100] i 2 == -1 给你两个字符串表示的复数 num1 和 num2 ,请你遵循复数表示形式,返回表示它们乘…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·string

bolt

答案摘要

我们可以将复数字符串转换成对应的实部 和虚部 ,然后根据复数乘法的公式 $(a_1 + b_1i) \times (a_2 + b_2i) = (a_1a_2 - b_1b_2) + (a_1b_2 + a_2b_1)i$ 计算出结果。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

复数 可以用字符串表示,遵循 "实部+虚部i" 的形式,并满足下述条件:

  • 实部 是一个整数,取值范围是 [-100, 100]
  • 虚部 也是一个整数,取值范围是 [-100, 100]
  • i2 == -1

给你两个字符串表示的复数 num1num2 ,请你遵循复数表示形式,返回表示它们乘积的字符串。

 

示例 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 的形式。 

 

提示:

  • num1num2 都是有效的复数表示。
lightbulb

解题思路

方法一:模拟

我们可以将复数字符串转换成对应的实部 aa 和虚部 bb,然后根据复数乘法的公式 (a1+b1i)×(a2+b2i)=(a1a2b1b2)+(a1b2+a2b1)i(a_1 + b_1i) \times (a_2 + b_2i) = (a_1a_2 - b_1b_2) + (a_1b_2 + a_2b_1)i 计算出结果。

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
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"
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

复数乘法题解:数学·string | LeetCode #537 中等