Problem statement:

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.

Solution one: DFS from back to front(AC)

The input is an expression in the format of string. We need to divide the entire problem into small size. By the rules of addition associative law, we can not loop from front to back since the sign need to reverse if it is negative. So, looping from back to front is a good idea.

DFS model:

In this problem, I choose the DFS template with a return value(string).

In each level, I get a string representing a fraction, add it with the return value from the lower level and return the sum(string) to upper level.

In order to get the string fraction in current level, I stop at '+', '-' or the beginning position of the string(this is only useful when the first number in the string is positive).

For the purpose of a readable code, there are two functions, one function adds two string fractions and returns a string, another gets the greatest common divisor of two positive integers and return a positive integer.

Some knowledge need to be remembered, these are all I met when I coded:

  • sscanf function:int sscanf ( const char * s, const char * format, ...);
  • this function inherits from C style, the first element is const char *.
  • string::resize(): return value is void, it can not be passed into a function as a parameter.
  • Greatest Common Divisor(GCD): in order to get the correct GCD, both inputs are positive.

Time complexity is O(n). n is the size of the input string.

class Solution {
public:
string fractionAddition(string expression) {
if(expression.empty()){
return "0/1";
}
string second;
for(int i = expression.size() - ; i >= ; i--){
if(expression[i] == '+' || expression[i] == '-' || i == ){
second = expression.substr(i);
break;
}
}
// resize the string
expression.resize(expression.size() - second.size());
string first = fractionAddition(expression);
return add(first, second);
}
private:
string add(string first, string second){
if(first.empty()){
return second;
}
int fn = , fd = , sn = , sd = ;
// get the number from expression
sscanf(first.c_str(), "%d/%d", &fn, &fd);
sscanf(second.c_str(), "%d/%d", &sn, &sd);
int numerator = fn * sd + fd * sn;
int denominator = fd * sd;
if(numerator == ){
return "0/1";
}
int gcd = get_gcd(abs(numerator), abs(denominator)); // all input must be position to get GCD
return to_string(numerator/gcd) + "/" + to_string(denominator/gcd);
}
// get greatest common divisor
// the two inputs should be positive
int get_gcd(int a, int b){
while(a != b){
if(a > b){
a -= b;
} else {
b -= a;
}
}
return a;
}
};

Solution two: 

This solution is intuitive, extract all fractions including their sign from the expression and push them into a vector, add them together.

Time complexity is O(n).

class Solution {
public:
string fractionAddition(string expression) {
vector<string> fractions;
for(int i = , j = ; j <= expression.size(); j++){
if(j == expression.size() || expression[j] == '+' || expression[j] == '-'){
fractions.push_back(expression.substr(i, j - i));
i = j;
}
}
string addition("0/1");
for(auto fraction : fractions){
addition = get_addition(addition, fraction);
}
return addition;
}
private:
string get_addition(string first, string second){
int fn = , fd = , sn = , sd = ;
// get the number from expression
sscanf(first.c_str(), "%d/%d", &fn, &fd);
sscanf(second.c_str(), "%d/%d", &sn, &sd);
int numerator = fn * sd + fd * sn;
int denominator = fd * sd;
if(numerator == ){
return "0/1";
}
int gcd = get_gcd(abs(numerator), abs(denominator)); // all input must be position to get GCD
return to_string(numerator/gcd) + "/" + to_string(denominator/gcd);
}
// get greatest common divisor
// the two inputs should be positive
int get_gcd(int a, int b){
while(a != b){
if(a > b){
a -= b;
} else {
b -= a;
}
}
return a;
}
};

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. LC 592. Fraction Addition and Subtraction

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

  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. MyEclipse2014+Maven配置记录

    一.MyEclipse配置Maven 打开MyEclipse2014,选择菜单:Window --> Preferences,选择:MyEclipse-Maven4MyEclipse-Insta ...

  2. Mybatis查询select操作

    先看select标签的属性: 说几点: resultType和resultMap都是用来表示结果集的类型的,resultType用于简单的HashMap或者是简单的pojo对象,而resultSet是 ...

  3. 【图片匹配】--- SIFT_Opencv3.1.0_C++_ubuntu

    最近在捣鼓图片相似性匹配算法.这里先说一点必要的题外话: 如果是在同一个object不同角度拍摄的多张图片中,使用SIFT可以有不错的效果: 如果是寻找类别相同的图片(可能不是同一object),SI ...

  4. 221 Maximal Square 最大正方形

    在一个由0和1组成的二维矩阵内,寻找只包含1的最大正方形,并返回其面积.例如,给出如下矩阵:1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0返回 4. 详见:https://l ...

  5. hdu3433A Task Process( 二分dp)

    链接 二分时间,在时间内dp[i][j]表示截止到第i个人已经做了j个A最多还能做多少个B #include <iostream> #include<cstdio> #incl ...

  6. ZOJ 3605Find the Marble(dp)

    ZOJ 3605 大体意思就是 找出随机选了K个交换后 石子在第i个罐子里的概率最大 也就是可能的总数最大 这样就可以写出递推方程 dp[i][j][k] += dp[i-1][e][k]; (0&l ...

  7. ADO.net增删改的使用

    添加数据 -------------------------------------------------- //让用户输入要添加的内容 Console.WriteLine("请输入要添加 ...

  8. swiper4初始化/swiper-init/data-swiper

    用data属性初始化swiper <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

  9. Python学习 Day 5 高阶函数 map/reduce filter sorter 返回函数 匿名函数 装饰器 偏函数

    高阶函数Higher-orderfunction 变量可以指向函数 >>> abs #abs(-10)是函数调用,而abs是函数本身 <built-in function ab ...

  10. vuex的应用和解决的实际问题

    这是vuex的语法结构内容 简单的理解vuex: new Vue({ // state data () { return { count: 0 } }, // view template: ` < ...