537. Complex Number Multiplication ¶ Time: Space: C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16class Solution { public: string complexNumberMultiply(string num1, string num2) { const auto& [a0, a1] = getReala0ndImag(num1); const auto& [b0, b1] = getReala0ndImag(num2); return to_string(a0 * b0 - a1 * b1) + "+" + to_string(a0 * b1 + a1 * b0) + "i"; } private: pair<int, int> getReala0ndImag(const string& s) { const string& real = s.substr(0, s.find_first_of('+')); const string& imag = s.substr(s.find_first_of('+') + 1); return {stoi(real), stoi(imag)}; }; }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14class Solution { public String complexNumberMultiply(String num1, String num2) { int[] a = getRealAndImag(num1); int[] b = getRealAndImag(num2); return String.valueOf(a[0] * b[0] - a[1] * b[1]) + "+" + String.valueOf(a[0] * b[1] + a[1] * b[0]) + "i"; } private int[] getRealAndImag(final String s) { final String real = s.substring(0, s.indexOf('+')); final String imag = s.substring(s.indexOf('+') + 1, s.length() - 1); return new int[] {Integer.valueOf(real), Integer.valueOf(imag)}; } } 1 2 3 4 5 6 7 8class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: a0, a1 = self._getReala0ndImag(num1) b0, b1 = self._getReala0ndImag(num2) return str(a0 * b0 - a1 * b1) + '+' + str(a0 * b1 + a1 * b0) + 'i' def _getReala0ndImag(self, s: str) -> tuple: return int(s[:s.index('+')]), int(s[s.index('+') + 1:-1])