Java Solution, Cross Products


  • 0
    public class Solution {
        public String complexNumberMultiply(String a, String b) {
            int[] aa = parseComplex(a);
            int[] bb = parseComplex(b);
            
            int real = aa[0] * bb[0] - aa[1] * bb[1];
            int imag = aa[0] * bb[1] + aa[1] * bb[0];
            
            String result = real + "+" + imag + "i";
            
            return result;
        }
        
        private int[] parseComplex(String s) {
            int[] res = new int[2];
            
            int i = 0, j = 1;
            while (j < s.length() && s.charAt(j) != '+') j++;
            res[0] = Integer.parseInt(s.substring(i, j));
            
            j++; i = j;
            while (j < s.length() && s.charAt(j) != 'i') j++;
            res[1] = Integer.parseInt(s.substring(i, j));
            
            return res;
        }
    }
    

  • 0

    you can use split() to parse the String. :)


Log in to reply
 

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