-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfractionAddition.java
More file actions
57 lines (49 loc) · 1.94 KB
/
fractionAddition.java
File metadata and controls
57 lines (49 loc) · 1.94 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
class Solution {
public String fractionAddition(String expression) {
// Initialize numerator and denominator for the result
int numerator = 0;
int denominator = 1;
// Use a scanner to parse the string
int index = 0;
while (index < expression.length()) {
// Parse the sign
int sign = 1;
if (expression.charAt(index) == '-' || expression.charAt(index) == '+') {
sign = expression.charAt(index) == '-' ? -1 : 1;
index++;
}
// Parse the numerator
int num = 0;
while (index < expression.length() && Character.isDigit(expression.charAt(index))) {
num = num * 10 + (expression.charAt(index) - '0');
index++;
}
// Move past the '/'
index++;
// Parse the denominator
int denom = 0;
while (index < expression.length() && Character.isDigit(expression.charAt(index))) {
denom = denom * 10 + (expression.charAt(index) - '0');
index++;
}
// Update the numerator and denominator for the result
numerator = numerator * denom + sign * num * denominator;
denominator = denominator * denom;
// Reduce the fraction by dividing by the greatest common divisor (GCD)
int gcd = gcd(Math.abs(numerator), denominator);
numerator /= gcd;
denominator /= gcd;
}
// Return the result in the required format
return numerator + "/" + denominator;
}
// Helper function to find the greatest common divisor (GCD) using Euclid's algorithm
private int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}