Thursday, January 24, 2019

Leetcode 537. Complex Number Multiplication

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.
Code (Java):
class Solution {
    public String complexNumberMultiply(String a, String b) {
        // parse the r and i
        //
        String delim = "[+]";
        String[] tokensA = a.split(delim);
        String[] tokensB = b.split(delim);

        // get real part
        //
        int r1 = getInteger(tokensA[0]);
        int r2 = getInteger(tokensB[0]);

        // get imiminary part
        //
        int i1 = getInteger(tokensA[1].substring(0, tokensA[1].length() - 1));
        int i2 = getInteger(tokensB[1].substring(0, tokensB[1].length() - 1));

        // compose the result
        //
        int r3 = r1 * r2 - i1 * i2;
        int i3 = r1 * i2 + r2 * i1;

        return r3 + "+" + i3 + "i";
    }

    private int getInteger(String s) {
        boolean isNeg = false;
        int i = 0;
        if (s.charAt(0) == '-') {
            isNeg = true;
            i++;
        }

        int result = 0;
        while (i < s.length()) {
            int digit = Character.getNumericValue(s.charAt(i));
            result = result * 10 + digit;
            i++;
        }

        if (isNeg) {
            result = -result;
        }

        return result;
    }
}

No comments:

Post a Comment