LuoJunC

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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:

  1. The input strings will not have extra blank.
  2. 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.

My Solution:

According to the multiplication rule of Complex Number, (a+bi)*(c+di)=(ac-bd)+(bc+ad)i, so:

public class Solution {
    public String complexNumberMultiply(String a, String b) {
        int num1,num2,num3,num4;
        num1 = Integer.parseInt(a.split("\\+")[0]);
        num2 = Integer.parseInt(a.split("\\+")[1].split("i")[0]);
        num3 = Integer.parseInt(b.split("\\+")[0]);
        num4 = Integer.parseInt(b.split("\\+")[1].split("i")[0]);
        
        int pre = num1*num3 - num2*num4;
        int aft = num2*num3 + num1*num4;
        
        return pre + "+" + aft + "i"; 
    }
}

Other's Solution:

public String complexNumberMultiply(String a, String b) {
    int[] coefs1 = Stream.of(a.split("\\+|i")).mapToInt(Integer::parseInt).toArray(), 
          coefs2 = Stream.of(b.split("\\+|i")).mapToInt(Integer::parseInt).toArray();
    return (coefs1[0]*coefs2[0] - coefs1[1]*coefs2[1]) + "+" + (coefs1[0]*coefs2[1] + coefs1[1]*coefs2[0]) + "i";
}

 

posted on 2017-04-05 14:57  LuoJunC  阅读(157)  评论(0编辑  收藏  举报