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:
- The input strings will not have extra blank.
- 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.
Python Solution 1:
class Solution(object):
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a_l, a_r = a.split('+')
b_l, b_r = b.split('+')
a_l = int(a_l)
a_r = int(a_r[:-1])
b_l = int(b_l)
b_r = int(b_r[:-1])
res_l = a_l * b_l - a_r * b_r
res_r = a_r * b_l + a_l * b_r
return str(res_l) + '+' + str(res_r) + 'i'
Python Solution 2:
class Solution(object):
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a_l, a_r = map(int, a[:-1].split('+'))
b_l, b_r = map(int, b[:-1].split('+'))
return "{}+{}i".format(a_l * b_l - a_r * b_r, a_r * b_l + a_l * b_r)
C Solution:
int part(char **_a, char delimiter) {
char *a = *_a;
int sign = 1;
int a_l = 0;
if (*a == '-') {
sign = -1;
a++;
}
while (*a != delimiter) {
a_l = a_l * 10 + *a++ - '0';
}
*_a = a + 1;
return a_l * sign;
}
char* complexNumberMultiply(char* a, char* b) {
int a_l = part(&a, '+');
int a_r = part(&a, 'i');
int b_l = part(&b, '+');
int b_r = part(&b, 'i');
int res_l = a_l * b_l - a_r * b_r;
int res_r = a_l * b_r + a_r * b_l;
char *res = malloc(11);
sprintf(res, "%d+%di", res_l, res_r);
return res;
}
Summary:
- Python is so convenient.
LeetCode: 537. Complex Number Multiplication





近期评论