Java OO Solution


  • 0

    I don't know why. I can not help writing it in an OO way...

    public class Solution {
        public class Complex{
            int real;
            int imaginary;
            
            public Complex(int a, int b){
                real = a;
                imaginary = b;
            }
            
            public Complex(String s){
                int sign = 1, num = 0, idx = 0;
                
                if(s.charAt(idx) == '-') {
                    sign = -1;
                    idx++;
                }
                
                while(s.charAt(idx) != '+'){
                    num = num*10+s.charAt(idx++)-'0';
                }
                
                real = sign*num;
                idx++;
                
                sign = 1;
                num = 0;
                if(s.charAt(idx) == '-') {
                    sign = -1;
                    idx++;
                }
                while(s.charAt(idx) != 'i'){
                    num = num*10+s.charAt(idx++)-'0';
                }
                
                imaginary = sign*num;
            }
            
            public Complex multiply(Complex comp){
                int a = real * comp.real - imaginary * comp.imaginary;
                int b = real * comp.imaginary + imaginary * comp.real;
                
                return new Complex(a,b);
            }
            
            public String toString(){
                return real+"+"+imaginary+"i";
            }
        }
        
        public String complexNumberMultiply(String a, String b) {
            Complex c1 = new Complex(a);
            Complex c2 = new Complex(b);
            Complex c3 = c1.multiply(c2);
            return c3.toString();
        }
    }
    

Log in to reply
 

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