-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution592.cs
69 lines (60 loc) · 1.95 KB
/
Solution592.cs
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
68
69
namespace LeetCode.Solutions;
public class Solution592
{
/// <summary>
/// 592. Fraction Addition and Subtraction - Medium
/// <a href="https://leetcode.com/problems/fraction-addition-and-subtraction">See the problem</a>
/// </summary>
public string FractionAddition(string expression)
{
int numerator = 0;
int denominator = 1; // Start with denominator as 1
int i = 0;
while (i < expression.Length)
{
// Determine the sign of the current fraction
int sign = 1;
if (expression[i] == '-' || expression[i] == '+')
{
sign = (expression[i] == '-') ? -1 : 1;
i++;
}
// Parse the numerator
int num = 0;
while (i < expression.Length && char.IsDigit(expression[i]))
{
num = num * 10 + (expression[i] - '0');
i++;
}
num *= sign; // Apply the sign to the numerator
// Skip the '/'
i++;
// Parse the denominator
int denom = 0;
while (i < expression.Length && char.IsDigit(expression[i]))
{
denom = denom * 10 + (expression[i] - '0');
i++;
}
// Add the current fraction (num/denom) to the running total (numerator/denominator)
numerator = numerator * denom + num * denominator;
denominator *= denom;
// Reduce the fraction by GCD
int gcd = GCD(Math.Abs(numerator), Math.Abs(denominator));
numerator /= gcd;
denominator /= gcd;
}
// Return the result in the form "numerator/denominator"
return numerator + "/" + denominator;
}
private int GCD(int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}