Very simple Java solution using basic complex number mutil rules


  • 0
    Q

    Follow the rules a+bi * c+di = (ac -bd) + (ad + bc) i.

    	public String complexNumberMultiply(String a, String b) {
    		String[] s1 = a.split("\\+");
    	    String[] s2 = b.split("\\+");
    		int num1 = convert(s1[0]);
    		int num2 = convert(s2[0]);
    		int c1 = convert(s1[1].substring(0, s1[1].length()-1));
    		int c2 = convert(s2[1].substring(0, s2[1].length()-1));
    		int num3 = num1 * num2 -(c1 * c2);
    		int c3 = num1 * c2 +  num2 * c1;
    		return num3 + "+" +c3 +"i";
    
    	}
    	private int convert(String str){
    		boolean flag = false;
    		if(str.charAt(0)=='-') flag =  true;
    		int num = 0;
    		for (int i = 0; i < str.length(); i++) {
    			if(i==0&&str.charAt(i)=='-') continue;
    			num = num * 10 + str.charAt(i)-'0';
    		}
    		if(flag) num =  -num;
    		return num;
    	}
    

Log in to reply
 

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