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:

  1. The input string only contains '0' to '9''/''+' and '-'. So does the output.
  2. Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
  3. 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.
  4. The number of given fractions will be in the range [1,10].
  5. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
Runtime: 8 ms, faster than 0.00% of C++ online submissions for Fraction Addition and Subtraction.
Memory Usage: 5.1 MB, less than 0.00% of C++ online submissions for Fraction Addition and Subtraction.
class Solution {
public:
long long gcd(long long a, long long b) {
if(a < b) return gcd(b,a);
if(b == ) return a;
return gcd(b, a%b);
}
string fractionAddition(string expression) {
vector<int> numerator;
vector<int> denominator;
int j = ;
bool positive = false;
if(expression[] >= '' && expression[] <= '') positive = true;
else {
positive = false;
j = ;
}
string tmp;
for(size_t i=j+; i<expression.size(); i++) {
if(expression[i] == '+' || expression[i] == '-') {
tmp = expression.substr(j, i-j);
size_t k;
for(k = ; k < tmp.size(); k++) {
if(tmp[k] == '/') break;
}
numerator.push_back(stoi(tmp.substr(,k)));
if(!positive) numerator[numerator.size()-] *= -;
positive = expression[i] == '+' ? true : false;
denominator.push_back(stoi(tmp.substr(k+)));
j = i+;
}
}
tmp = expression.substr(j,expression.size()-j);
size_t k;
for(k=; k<tmp.size(); k++)
if(tmp[k] == '/') break;
numerator.push_back(stoi(tmp.substr(,k)));
if(!positive) numerator[numerator.size()-] *= -;
denominator.push_back(stoi(tmp.substr(k+)));
// test long long ret_numer = numerator[];
long long ret_denomi = denominator[];
long long r = ;
for(size_t i= ; i<denominator.size(); i++) {
long long tmp_deno = ret_denomi;
ret_denomi *= denominator[i];
ret_numer = ret_numer * denominator[i] + tmp_deno * numerator[i];
}
if(ret_numer > ) {
r = gcd(ret_numer, ret_denomi);
ret_numer /= r;
ret_denomi /= r;
} else if (ret_numer < ) {
r = gcd(-ret_numer, ret_denomi);
ret_numer /= r;
ret_denomi /= r;
} else if(ret_numer == ) {
ret_denomi = ;
}
string str_numer = ret_numer < ? ("-" + to_string(-ret_numer)) : to_string(ret_numer);
string str_deno = to_string(ret_denomi);
return str_numer + "/" + str_deno;
}
};

更好的一个思路

class Solution {
public:
string fractionAddition(string expression) {
istringstream iss(expression);
int num = , den = , NUM = , DEN = ;
char c;
while (iss >> num >> c >> den)
{
NUM = NUM * den + num * DEN;
DEN *= den;
int g = abs(gcd(NUM, DEN));
NUM /= g;
DEN /= g;
} return to_string(NUM) + "/" + to_string(DEN);
} int gcd(int x, int y)
{
return y == ? x : gcd(y, x % y);
}
};

LC 592. Fraction Addition and Subtraction的更多相关文章

  1. 【LeetCode】592. Fraction Addition and Subtraction 解题报告(Python)

    [LeetCode]592. Fraction Addition and Subtraction 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuem ...

  2. [LeetCode] 592. Fraction Addition and Subtraction 分数加减法

    Given a string representing an expression of fraction addition and subtraction, you need to return t ...

  3. 592. Fraction Addition and Subtraction

    Problem statement: Given a string representing an expression of fraction addition and subtraction, y ...

  4. 【leetcode】592. Fraction Addition and Subtraction

    题目如下: 解题思路:本题考察的是分数的加减法.小学时候就学过,分数的加减法是先求两个分母的最小公倍数,然后分子分别乘以最小公倍数与自己分母的商,相加后约分即可.所以,本题只要按+,-两个符号分割输入 ...

  5. [LeetCode] Fraction Addition and Subtraction 分数加减法

    Given a string representing an expression of fraction addition and subtraction, you need to return t ...

  6. [Swift]LeetCode592. 分数加减运算 | Fraction Addition and Subtraction

    Given a string representing an expression of fraction addition and subtraction, you need to return t ...

  7. [leetcode-592-Fraction Addition and Subtraction]

    Given a string representing an expression of fraction addition and subtraction, you need to return t ...

  8. 大数据加减(Big data addition and subtraction)

    题目描述 Description 加减法是计算中的基础运算,虽然规则简单,但是位数太多了,也难免会出错.现在的问题是:给定任意位数(不超过1000位)的加减法算式,请给出正确结果.为提高速度,保证给定 ...

  9. Arc066_E Addition and Subtraction Hard

    传送门 题目大意 给定一个加减法的表达式,让你任意的添加合法的括号对,使的表达式最大. 题解 考虑到任意左括号一定加在减号右边,那么对于第一个左括号,与该左括号相邻的只含有加号的子序列的贡献一定为负, ...

随机推荐

  1. IDEA 使用与总结

    一.IDEA和常用软件下载1.IDEA激活码网站:http://idea.lanyus.com/常用软件网站 idea : https://www.jetbrains.com/idea/downloa ...

  2. 猫眼 top_100 爬取 ___只完成了第一页

    # python 3.7 from urllib.request import Request,urlopen import time,re,csv class Maoyan(object): def ...

  3. 用js刷剑指offer(二叉树的镜像)

    题目描述 操作给定的二叉树,将其变换为源二叉树的镜像. 输入描述: 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ ...

  4. Paper Reading:TridentNet

    论文:Scale-Aware Trident Networks for Object Detection 发表时间:2019 发表作者:(University of Chinese Academy o ...

  5. DeviceSupport 路径

    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSuppor

  6. 解决使用JPA时对象在set属性时更新了数据库问题

    https://www.jianshu.com/p/1100814ff54f 之前也遇到过一次这个问题,打印的日志中也可以看见update相关的sql语句,但当时不知道为什么会去自动更新,就用了别的方 ...

  7. ES使用org.elasticsearch.client.transport.NoNodeAvailableException: No node available

    1) 端口错 client = new TransportClient().addTransportAddress(new InetSocketTransportAddress(ipAddress, ...

  8. Django传递数据给JS

    这里讲述两种方法: 一,页面加载完成后,在页面上操作,在页面上通过 ajax 方法得到新的数据(再向服务器发送一次请求)并显示在网页上,这种情况适用于页面不刷新的情况下,动态加载一些内容.比如用户输入 ...

  9. border-style

    border-style 语法: border-style:<line-style>{1,4} <line-style> = none | hidden | dotted | ...

  10. C# 使用多线程,在关闭窗体时 怎么关闭窗体的所有线程,使程序退出。

    this.Close();   只是关闭当前窗口,若不是主窗体的话,是无法退出程序的,另外若有托管线程(非主线程),也无法干净地退出: Application.Exit();  强制所有消息中止,退出 ...