题目描述思路
模拟
Python实现Java实现
题目描述
复数乘法
思路 模拟
对于给定的两个复数num1和num2,首先分别得到两个复数的实部和虚部,然后计算两个复数的乘法。用real1和imag1分别表示num1的实部和虚部,用real2,和imag2分别表示num2的实部和虚部,则乘法计算结果为
( r e a l 1 + i m a g 1 ∗ i ) ∗ ( r e a l 2 + i m a g 2 ∗ i ) = ( r e a l 1 ∗ r e a l 2 − i m a g 1 ∗ i m a g 2 ) + ( r e a l 1 ∗ i m a g 2 + r e a l 2 ∗ i m a g 1 ) ∗ i (real1+imag1*i) * (real2+imag2*i) = (real1*real2-imag1*imag2) + (real1*imag2+real2*imag1) * i (real1+imag1∗i)∗(real2+imag2∗i)=(real1∗real2−imag1∗imag2)+(real1∗imag2+real2∗imag1)∗i
得到乘积后,将乘积转为字符串形式返回。
class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: real1, imag1 = map(int, num1[:-1].split('+')) real2, imag2 = map(int, num2[:-1].split('+')) return f'{real1*real2-imag1*imag2}+{real1*imag2+imag1*real2}i'
Java实现class Solution { public String complexNumberMultiply(String num1, String num2) { String[] complex1 = num1.split("\+|i"); String[] complex2 = num2.split("\+|i"); int real1 = Integer.parseInt(complex1[0]), imag1 = Integer.parseInt(complex1[1]); int real2 = Integer.parseInt(complex2[0]), imag2 = Integer.parseInt(complex2[1]); return String.format("%d+%di", real1*real2-imag1*imag2, real1*imag2+real2*imag1); }}