leetcode/0537.Complex-Number-Multiplication/README.md
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:
给定两个表示复数的字符串。返回表示它们乘积的字符串。注意,根据定义 i^2 = -1 。
注意:
package leetcode
import (
"strconv"
"strings"
)
func complexNumberMultiply(a string, b string) string {
realA, imagA := parse(a)
realB, imagB := parse(b)
real := realA*realB - imagA*imagB
imag := realA*imagB + realB*imagA
return strconv.Itoa(real) + "+" + strconv.Itoa(imag) + "i"
}
func parse(s string) (int, int) {
ss := strings.Split(s, "+")
r, _ := strconv.Atoi(ss[0])
i, _ := strconv.Atoi(ss[1][:len(ss[1])-1])
return r, i
}