LeetCode in Kotlin

537. Complex Number Multiplication

Medium

A complex number can be represented as a string on the form "**real**+**imaginary**i" where:

Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.

Example 1:

Input: num1 = “1+1i”, num2 = “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: num1 = “1+-1i”, num2 = “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.

Constraints:

Solution

class Solution {
    fun complexNumberMultiply(num1: String, num2: String): String {
        val countReal: Int
        val countImagine: Int
        val arr1 = IntArray(2)
        val arr2 = IntArray(2)
        arr1[0] = num1.substring(0, num1.indexOf("+")).toInt()
        arr1[1] = num1.substring(num1.indexOf("+") + 1, num1.length - 1).toInt()
        arr2[0] = num2.substring(0, num2.indexOf("+")).toInt()
        arr2[1] = num2.substring(num2.indexOf("+") + 1, num2.length - 1).toInt()
        countReal = arr1[0] * arr2[0] - arr1[1] * arr2[1]
        countImagine = arr1[0] * arr2[1] + arr1[1] * arr2[0]
        return countReal.toString() + "+" + countImagine + "i"
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy