Back to Leetcode Go

537. Complex Number Multiplication

website/content.en/ChapterFour/0500~0599/0537.Complex-Number-Multiplication.md

1.7.971.9 KB
Original Source

537. Complex Number Multiplication

Problem

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:

  1. The input strings will not have extra blank.
  2. 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.

Problem Summary

Given two strings representing complex numbers. Return a string representing their product. Note that, by definition, i^2 = -1.

Note:

  • The input strings do not contain extra spaces.
  • The input strings will be given in the form a+bi, where the integers a and b are both in the range [-100, 100]. The output should also follow this form.

Solution Approach

  • Given 2 strings, compute the product of these two complex numbers, and output it in string format.
  • This is a math problem. Follow the arithmetic rules for complex numbers: i^2 = -1, and finally output the result as a string.

Code

go

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
}