public class Solution { private int GCD(int a, int b) { return b != 0 ? GCD(b, a % b) : a; } private int LCM(int a, int b) { return a * b / GCD(a, b); } public string FractionAddition(string expression) { var first = expression[0]; var FU = true;//默认当前表达式为负 if (first != '-') { FU = false;//当前表达式为正 } var listPOS = new List<string>();//记录正表达式 var listNev = new List<string>();//记录负表达式 //先将正表达式和负表达式分开 var sb = new StringBuilder();//记录当前表达式 for (int i = 0; i < expression.Length; i++) { if (expression[i] == '-') { if (FU) { if (sb.Length > 0) { listNev.Add(sb.ToString()); } } else { if (sb.Length > 0) { listPOS.Add(sb.ToString()); } } FU = true; sb.Clear(); } else if (expression[i] == '+') { if (FU) { if (sb.Length > 0) { listNev.Add(sb.ToString()); } } else { if (sb.Length > 0) { listPOS.Add(sb.ToString()); } } FU = false; sb.Clear(); } else { sb.Append(expression[i]); } } if (FU) { if (sb.Length > 0) { listNev.Add(sb.ToString()); } } else { if (sb.Length > 0) { listPOS.Add(sb.ToString()); } } var listPOSSP = new List<List<int>>(); foreach (var str in listPOS) { var ary = str.Split('/'); var tp = new List<int>(); tp.Add(int.Parse(ary[1])); tp.Add(int.Parse(ary[0])); listPOSSP.Add(tp); } var listNEVSP = new List<List<int>>(); foreach (var str in listNev) { var ary = str.Split('/'); var tp = new List<int>(); tp.Add(int.Parse(ary[1])); tp.Add(int.Parse(ary[0])); listNEVSP.Add(tp); } var lcm1 = 1; var sumPOS = 0; if (listPOSSP.Any()) { if (listPOSSP.Count == 1) { lcm1 = listPOSSP[0][0]; } else { lcm1 = listPOSSP[0][0]; for (int i = 1; i < listPOSSP.Count; i++) { var curFM = listPOSSP[i][0]; lcm1 = LCM(lcm1, curFM); } } for (int i = 0; i < listPOSSP.Count; i++) { var FM = listPOSSP[i][0]; var FZ = listPOSSP[i][1]; var bs = lcm1 / FM; FZ = FZ * bs; sumPOS += FZ; } } var lcm2 = 1; var sumNEV = 0; if (listNEVSP.Any()) { if (listNEVSP.Count == 1) { lcm2 = listNEVSP[0][0]; } else { lcm2 = listNEVSP[0][0]; for (int i = 1; i < listNEVSP.Count; i++) { var curFM = listNEVSP[i][0]; lcm2 = LCM(lcm2, curFM); } } for (int i = 0; i < listNEVSP.Count; i++) { var FM = listNEVSP[i][0]; var FZ = listNEVSP[i][1]; var bs = lcm2 / FM; FZ = FZ * bs; sumNEV += FZ; } } var lcm = LCM(lcm1, lcm2); var bs1 = lcm / lcm1; var bs2 = lcm / lcm2; var fz1 = sumPOS * bs1; var fz2 = sumNEV * bs2; var fz = fz1 - fz2; var cc = GCD(fz, lcm); if (cc < 0) { cc = cc * -1; } var result = fz / cc + "/" + lcm / cc; return result; } }
https://leetcode.com/problems/fraction-addition-and-subtraction/#/description