[leetcode-592-Fraction Addition and Subtraction]
Posted hellowOOOrld
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-592-Fraction Addition and Subtraction]相关的知识,希望对你有一定的参考价值。
Given a string representing an expression of fraction addition and subtraction,
you need to return the calculation result in string format. The final result should be irreducible fraction.
If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1.
So in this case, 2 should be converted to 2/1.
Example 1:
Input:"-1/2+1/2"
Output: "0/1"
Example 2:
Input:"-1/2+1/2+1/3"
Output: "1/3"
Example 3:
Input:"1/3-1/2"
Output: "-1/6"
Example 4:
Input:"5/3+1/3"
Output: "2/1"
Note:
The input string only contains ‘0‘ to ‘9‘, ‘/‘, ‘+‘ and ‘-‘. So does the output.
Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then ‘+‘ will be omitted.
The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
The number of given fractions will be in the range [1,10].
The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
思路:
如下是参考一 大神给出的代码,先贴这儿,慢慢学习:
string fractionAddition(string s) { long p = 0, q = 1, p1, q1, t; for (size_t i = 0, j; i < s.size(); i = j) { j = s.find_first_of("+-", i+1); if (j == string::npos) j = s.size(); auto k = s.find(‘/‘, i); long x = stol(s.substr(i, k-i)), y = stol(s.substr(k+1, j)); p1 = p*y+q*x; q1 = q*y; t = __gcd(p1, q1); p = p1/t; q = q1/t; if (q < 0) p *= -1, q *= -1; } return to_string(p)+"/"+to_string(q); }
如下是leetcode上的solution。
The initial fraction is 0/1 (n/d). We just need to read next fraction (nn/dd), normalize denominators between n/d and nn/dd (using GCD), and add/subtract the numerator (n +/- nn). In the end, we also need to use GCD to make the resulting fraction irreducible.
int GCD(int a, int b ){ return (b == 0) ? a : GCD(b, a % b); } string fractionAddition(string s) { int n = 0, d = 1, p = 0, p1 = 0, p2 = 0; if (s[0] != ‘-‘) s = "+" + s; while (p < s.size()) { for (p1 = p + 1; s[p1] != ‘/‘; ++p1); for (p2 = p1 + 1; p2 < s.size() && s[p2] != ‘+‘ && s[p2] != ‘-‘; ++p2); auto nn = stoi(s.substr(p + 1, p1 - p - 1)), dd = stoi(s.substr(p1 + 1, p2 - p1 - 1)); auto gcd = GCD(d, dd); n = n * dd / gcd + (s[p] == ‘-‘ ? -1 : 1) * nn * d / gcd; d *= dd / gcd; p = p2; } auto gcd = GCD(abs(n), d); return to_string(n / gcd) + "/" + to_string(d / gcd); }
参考:
https://discuss.leetcode.com/topic/90024/c-12-lines-gcd
以上是关于[leetcode-592-Fraction Addition and Subtraction]的主要内容,如果未能解决你的问题,请参考以下文章
C6678+K7+AD9253/AD9783 8路AD高速信号处理板