Java 5ms beats 95.84% Most Straightforward


  • 0
    S
    public class Solution {
        public String complexNumberMultiply(String a, String b) {
            int[] arr1 = getDigit(a);
            int[] arr2 = getDigit(b);
            int A = arr1[0], B = arr1[1];
            int C = arr2[0], D = arr2[1];
    
            int real = A*C - D*B;
            int imag = A*D + B*C;
            
            return ""+real+"+"+imag+"i";
        }
        private int[] getDigit (String s) {
            int[] res = new int[2];
            int i = 0;
            if (s.charAt(i) == '-') {
                i++;
                while (s.charAt(i)!='+') {
                    res[0] = res[0]*10 + s.charAt(i) - '0';
                    i++;
                }
                res[0] = -res[0];
            }
            else {
                while (s.charAt(i)!='+') {
                    res[0] = res[0]*10 + s.charAt(i) - '0';
                    i++;
                }
            }
            
            if (s.charAt(++i) == '-') {
                i++;
                while (i < s.length()-1) {
                    res[1] = res[1]*10 + s.charAt(i) - '0';
                    i++;
                }
                res[1] = -res[1];
            }
            else {
                while (i < s.length()-1) {
                    res[1] = res[1]*10 + s.charAt(i) - '0';
                    i++;
                }
            }
            return res;
        }
    }
    

    You can replace the getDigit Method with the following short one:

     private int[] getDigit (String s) {
            int[] res = new int[2];
            String[] str = s.split("\\+");
            res[0] = Integer.parseInt(str[0]);
            res[1] = Integer.parseInt(str[1].substring(0,str[1].length()-1));
            return res;
        }
    

Log in to reply
 

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