Complex Number Multiplication

Given two Strings representing two complex number, return a string representing their multiplication.

The given strings are in the form of a+bi and the result should also be in that form.

e.g.: 3+4i, -2+0i, 0+-1i;

Solution:

1. split the two given strings into the form of two integers representing the real part and the imaginary part respectively.

Use the split function of string and the parseInt function of Integer.

As '+' is a symbol we need to transfer meaning of it using '\' and also need to transfer meaning of '\' using '\'  -> "\\+"

2. calculate the real part and the imaginary part of the result.

3. build the new string as real+"+"+imaginary+"i"

Code:

public class Solution {
    public String complexNumberMultiply(String a, String b) {
        int[] para_a = complexToArray(a), para_b = complexToArray(b);
        int non_complex = para_a[0]*para_b[0]-para_a[1]*para_b[1];
        int complex_part = para_a[0]*para_b[1]+para_a[1]*para_b[0];
        StringBuilder sb = new StringBuilder();
        sb.append(non_complex);
        sb.append('+');
        sb.append(complex_part);
        sb.append('i');
        return sb.toString();
    }
    private int[] complexToArray(String s){
        String[] arr = s.split("\\+");
        int[] result = new int[2];
        result[0] = Integer.parseInt(arr[0]);
        result[1] = Integer.parseInt(arr[1].substring(0,arr[1].length()-1));
        return result;
    }
}
View Code

 

posted @ 2017-06-17 01:19  小风约定  阅读(54)  评论(0)    收藏  举报