forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComplexNumberMultiplication.java
58 lines (51 loc) · 1.38 KB
/
ComplexNumberMultiplication.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution {
// T C : O(len1) + O(len2)
private class ComplexNo{
private int rNo;
private int iNo;
public ComplexNo(int rNo, int iNo){
this.rNo = rNo;
this.iNo = iNo;
}
}
public String complexNumberMultiply(String num1, String num2) {
ComplexNo no1 = parseNo(num1);
ComplexNo no2 = parseNo(num2);
int rProductNo = (no1.rNo * no2.rNo) - (no1.iNo * no2.iNo);
int iProductNo = (no1.iNo * no2.rNo) + (no1.rNo * no2.iNo) ;
String ans = rProductNo + "+"+ iProductNo+ "i";
return ans;
}
private ComplexNo parseNo(String no){
int i=0;
int rNo = 0;
boolean isNegReal = false;
if(no.charAt(i) == '-'){
isNegReal = true;
i++;
}
while(no.charAt(i) !='+'){
rNo = 10*rNo + (no.charAt(i) - '0');
i++;
}
if(isNegReal){
rNo = -rNo;
}
i++; // +
boolean isNegImg = false;
if(no.charAt(i)=='-'){
isNegImg = true;
i++;
}
int iNo = 0;
while(no.charAt(i)!='i'){
// System.out.println(no.charAt(i));
iNo = 10*iNo + (no.charAt(i) - '0');
i++;
}
if(isNegImg){
iNo = -iNo;
}
return new ComplexNo(rNo,iNo);
}
}