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. 【Hibernate】检索方式

    一.概述 二.HQL 2.1 简介 2.2 查询所有记录 2.3 查询使用别名 2.4 排序 2.5 分页查询 2.6 单个对象查询 2.7 参数绑定 2.8 投影操作 2.9 模糊查询 2.10 S ...

  2. python3使用ConfigParser从配置文件中获取列表

    使用python3使用ConfigParser从配置文件中获取列表 testConfig.py #!/usr/bin/env python # coding=utf- __author__ = 'St ...

  3. 用js刷剑指offer(变态跳台阶)

    一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级.求该青蛙跳上一个n级的台阶总共有多少种跳法. 牛客网链接 思路 假设青蛙跳上一个n级的台阶总共有f(n)种跳法. 现在青蛙从第n个台阶 ...

  4. 《流畅的Python》Data Structures--第7章 colsure and decorator

    Function Decorators and Closures 装饰器是用于增强函数的行为,理解它,就必须先理解闭包. Python3引入关键字nonlocal,如果要理解闭包,就必须了解它的所有方 ...

  5. flask 杂记

    参考资料:http://python.jobbole.com/84003/  https://flask-cn.readthedocs.io/en/latest/tutorial/ 加载配置: app ...

  6. 通过Chrome控制台详细查看ajax请求

    1.F12打开浏览器开发者工具 2.如图所示

  7. c++ string类基本使用

    初始化用法 #include <iostream> #include "string" using namespace std; void main() { strin ...

  8. System.Web.HttpRequestValidationException: 从客户端(name="<a href=''>我是晓菜鸟</a>")中检测到有潜在危险的 Request.Form 值

    这是一个比较常见的问题了,如果Web表单中有输入类似于 Html 标签之类的文本,在通过 Request.QueryString 或者 Request.Form 传递这些值的时候,就会触发这样的异常, ...

  9. 04_mysql安装

    # 安装 [root@localhost ~]# yum install mysql mysql-server -y 报错 [root@ossec-server ~]# yum install mys ...

  10. C语言学习系列(六)基本语法

    一.C运算符 算术运算符(语法和java类似或基本一样略过不再描述) 关系运算符(略) 逻辑运算符(略) 位运算符 运算符 描述 实例 & 如果同时存在于两个操作数中,二进制 AND 运算符复 ...