Java easy to understand solution


  • 0
    J
    public class Solution {
        public String complexNumberMultiply(String a, String b) {
            // (a+bi)(c+di)= ac + adi + bci - bd = (ac - bd) + (ad + bc)i
            
            String[] partsA = a.split("\\+");
            int av = Integer.parseInt(partsA[0]);
            int bv = Integer.parseInt(partsA[1].replace("i",""));
            String[] partsB = b.split("\\+");
            int cv = Integer.parseInt(partsB[0]);
            int dv = Integer.parseInt(partsB[1].replace("i",""));
            
            int real = av*cv - bv*dv;
            int imaginary = av*dv + bv*cv;
            return String.valueOf(real) + "+" + String.valueOf(imaginary) + "i";
        }
    }
    

Log in to reply
 

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