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. python_数据类型基本操作(2)

    概览: 第1章 基础数据类型宏观的初识第2章 int 第3章 bool 第4章 str 4.1 python体现形式 4.2 引号用法 4.3 字符串运算 4.3.1 字符串相加 4.3.2 字符串相 ...

  2. 转】MongoDB 自动分片 auto sharding

    原博文出自于: http://blog.fens.me/category/%E6%95%B0%E6%8D%AE%E5%BA%93/page/4/ 感谢! MongoDB 自动分片 auto shard ...

  3. ATM机(非函数版)

    #include<stdio.h>#include<stdlib.h>int main(void){char zhangHao[]="123";int mi ...

  4. [转]Php MySql Class

    本文转自:http://www.cnblogs.com/noevil/archive/2010/11/06/1870864.html <?php /**  * 数据库操作类  *  * @aut ...

  5. java-IO操作性能对比

    在软件系统中,IO速度比内存速度慢,IO读写在很多情况下会是系统的瓶颈. 在java标准IO操作中,InputStream和OutputStream提供基于流的IO操作,以字节为处理单位:Reader ...

  6. JSP标签 <meta.....>作用总结

    <metahttp-equiv="pragma" content="no-cache"> <metahttp-equiv="cach ...

  7. 高仿人人网客户端Android版项目源码

    高仿人人网客户端,有兴趣的盆友可以研究下,里面主要包含的一些UI设计与交互.(注:项目中有少许问题,apk能运行,希望开发者可以参考代码研究一下.) 源码下载:http://code.662p.com ...

  8. win+r 快速命令

    control keymgr.dll   打开凭据管理器 secpol.msc   本地安全策略 mstsc   远程 msconfig   启动选项 %temp%   临时文件夹 \\192.168 ...

  9. webstorm快捷键大全-webstorm常用快捷键

    默认配置下的常用快捷键,提高代码编写效率,离不开快捷键的使用,Webstorm拥有丰富的代码快速编辑功能,你可以自由配置功能快捷键. Webstorm预置了其他编辑器的快捷键配置,可以点击 查找/代替 ...

  10. python学习第三次

    while循环 表示当条件成立的时候就循环适用于不知道具体循环次数,但是确定在某个条件成立的情况下就循环while语法:while 条件表达式:语句块#另一种表达方式while 条件表达式:语句块1e ...