Complex Number Multiplication
Problem
Given two complex numbers as strings 'a+bi', return their product in the same format.
num1 = "1+1i", num2 = "1+1i""0+2i"def complex_number_multiply(a, b):
def parse(s):
s = s[:-1] # drop 'i'
i = s.index("+", 1) if s[0] == "-" else s.index("+")
return int(s[:i]), int(s[i+1:])
ar, ai = parse(a); br, bi = parse(b)
return f"{ar*br - ai*bi}+{ar*bi + ai*br}i"
function complexNumberMultiply(a, b) {
function parse(s) {
s = s.slice(0, -1);
const i = s.indexOf("+", 1);
return [Number(s.slice(0, i)), Number(s.slice(i + 1))];
}
const [ar, ai] = parse(a), [br, bi] = parse(b);
return `${ar * br - ai * bi}+${ar * bi + ai * br}i`;
}
class Solution {
public String complexNumberMultiply(String a, String b) {
int[] x = parse(a), y = parse(b);
return (x[0]*y[0] - x[1]*y[1]) + "+" + (x[0]*y[1] + x[1]*y[0]) + "i";
}
int[] parse(String s) {
s = s.substring(0, s.length() - 1);
int i = s.indexOf('+', 1);
return new int[]{ Integer.parseInt(s.substring(0, i)), Integer.parseInt(s.substring(i + 1)) };
}
}
pair parse(string s) {
s.pop_back();
int p = s.find('+', 1);
return { stoi(s.substr(0, p)), stoi(s.substr(p + 1)) };
}
string complexNumberMultiply(string a, string b) {
auto [ar, ai] = parse(a);
auto [br, bi] = parse(b);
return to_string(ar*br - ai*bi) + "+" + to_string(ar*bi + ai*br) + "i";
}
Explanation
The task is mostly parsing two strings like "a+bi" into numbers, then applying the standard formula for multiplying complex numbers.
The helper parse drops the trailing i, finds the + that separates the real and imaginary parts, and returns the two integers. We search for + starting at index 1 so a leading minus sign on the real part is not mistaken for the separator.
Multiplying (a + b·i)(c + d·i) and using i² = -1 gives a real part ac - bd and an imaginary part ad + bc. The code computes exactly these and formats them back as "(real)+(imag)i".
Example: "1+1i" times "1+1i" parses to a=1, b=1, c=1, d=1. Real part is 1·1 - 1·1 = 0 and imaginary part is 1·1 + 1·1 = 2, so the result string is "0+2i".
Because each string is short and we touch each character a constant number of times, the work is tiny and proportional to the input length.