Straightforward Java


  • 0
    C

    Time: O(N + M) where N is the length of String a and M is the length of String b.
    Space: O(N + M) where N is the length of String a and M is the length of String b.

    public class Solution {
        public String complexNumberMultiply(String a, String b) {
            String delim = "\\+";
            String i = "i";
            String[] aa = a.split(delim);
            String[] bb = b.split(delim);
            // parse real part
            int lRe = Integer.parseInt(aa[0]);
            int rRe = Integer.parseInt(bb[0]);
            // parse imaginary part
            int lIm = Integer.parseInt(aa[1].replace(i, ""));
            int rIm = Integer.parseInt(bb[1].replace(i, ""));
            // multiply
            int sumReRe = lRe * rRe;
            int sumReIm = lRe * rIm;
            int sumImRe = lIm * rRe;
            int sumImIm = lIm * rIm * -1;
            // construct result
            int sumRe = sumReRe + sumImIm;
            int sumIm = sumReIm + sumImRe;
            String reStr = ""+sumRe;
            String imStr = ""+sumIm;
            String result = reStr+"+"+imStr+"i";
            
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.