Skip to main content
Back to problems
#537
Medium Algorithms

Complex number multiplication

Math String Simulation
73.2% acceptance
Feb 19, 2026
755
1257
A complex number can be represented as a string on the form "real+imaginaryi" where: real is the real part and is an integer in the range [-100, 100]. imaginary is the imaginary part and is an integer in the range [-100, 100]. i2 == -1. Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn complex_number_multiply(num1: String, num2: String) -> String {
    fn parse(s: &str) -> (i32, i32) {
      let s = &s[..s.len()-1]; // remove trailing 'i'
      let bytes = s.as_bytes();
      let mut pos = bytes.len();
      for j in 1..bytes.len() {
        if bytes[j] == b'+' { pos = j; break; }
      }
      let real: i32 = s[..pos].parse().unwrap();
      let imag: i32 = s[pos+1..].parse().unwrap();
      (real, imag)
    }
    let (r1, i1) = parse(&num1);
    let (r2, i2) = parse(&num2);
    format!("{}+{}i", r1*r2 - i1*i2, r1*i2 + i1*r2)
  }
}