forked from RyanFehr/HackerRank
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
Latest commit
67 lines (59 loc) · 1.98 KB
/
Copy pathSolution.java
File metadata and controls
67 lines (59 loc) · 1.98 KB
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
59
60
61
62
63
64
65
66
67
// Problem: https://www.hackerrank.com/challenges/complex-numbers/problem
// Java 7
// Thoughts: Basic complex number operations
importjava.util.Scanner;
classComplex {
privatedoublere, im;
publicComplex(doublere, doubleim) {
this.re = re;
this.im = im;
}
publicComplexadd(Complexy) {
Complexresult = newComplex(this.re + y.re, this.im + y.im);
returnresult;
}
publicComplexsubtract(Complexy) {
Complexresult = newComplex(this.re - y.re, this.im - y.im);
returnresult;
}
publicComplexmultiply(Complexy) {
doublere1 = this.re * y.re;
doubleim1 = this.re * y.im;
doubleim2 = this.im * y.re;
doublere2 = this.im * y.im * -1; // -1 is the replacement of i squared
Complexresult = newComplex(re1 + re2, im1 + im2);
returnresult;
}
publicComplexdivide(Complexy) {
ComplexconjugateY = newComplex(y.re, y.im * -1);
Complexnumerator = multiply(conjugateY);
doubledenominator = Math.pow(y.re, 2) + Math.pow(y.im, 2);
Complexresult = newComplex(numerator.re / denominator, numerator.im / denominator);
returnresult;
}
publicComplexmod() {
doubleabsoluteValue = Math.abs(Math.sqrt(Math.pow(this.re, 2) + Math.pow(this.im, 2)));
Complexresult = newComplex(absoluteValue, 0);
returnresult;
}
publicStringtoString() {
returnString.format("%.2f%s%.2fi", re, im >= 0 ? "+" : "", im);
}
}
publicclassMain {
publicstaticvoidmain(String[] args) {
Scannerin = newScanner(System.in);
double[] re = newdouble[2], im = newdouble[2];
for (inti = 0; i < 2; ++i) {
re[i] = in.nextDouble();
im[i] = in.nextDouble();
}
Complexx = newComplex(re[0], im[0]), y = newComplex(re[1], im[1]);
System.out.println(x.add(y));
System.out.println(x.subtract(y));
System.out.println(x.multiply(y));
System.out.println(x.divide(y));
System.out.println(x.mod());
System.out.println(y.mod());
}
}