Sharing my java code


  • 0
    B

    Did not see any problem here except escaping "+" when calling split

    public String complexNumberMultiply(String a, String b) {
        
        //(a+bi)*(c+di) = ac + bdi^2 + (bc+ad)i = (ac - bd) + (bc+ad)i
        
        String[] ra = a.split("\\+");
        int xa = Integer.valueOf(ra[0]);
        int ya = Integer.valueOf(ra[1].substring(0, ra[1].length() - 1));
    
        String[] rb = b.split("\\+");
        int xb = Integer.valueOf(rb[0]);
        int yb = Integer.valueOf(rb[1].substring(0, rb[1].length() - 1));
        
        int xRet = (xa*xb - ya*yb);
        
        int yRet = (ya*xb + yb*xa);
        
        StringBuffer ret = new StringBuffer();
        ret.append(xRet);
        ret.append("+");
        ret.append(yRet);
        ret.append("i");
        
        return ret.toString();
    }

Log in to reply
 

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