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. 题解报告:hdu 2062 Subset sequence

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2062 Problem Description 考虑集合An = {1,2,...,n}. 例如,A1 ...

  2. java getDocumentBase() 得到的文件夹路径

    参考一个百度知道上的回答 举例说来,假设你的项目文件是xx,而这个xx文件夹是在D盘下的yy文件夹里,即项目文件的完整路径D:\yy\xx,则编译运行文件后,在xx文件夹里会产生名为build的文件夹 ...

  3. rsync常见错误

    rsync使用时的常见问题: 错误1: rsync: read error: Connection reset by peer (104) rsync error: error in rsync pr ...

  4. CSS ul li a 背景图片与文字对齐

    <div class="four"> <h2>电子商务</h2> <img src="images/photo2.gif&quo ...

  5. String的用法——获取功能

    package cn.itcast_04; /* String类获取功能 int length():获取字符的长度 char charAt(int index):获取指定索引位置的字符 int ind ...

  6. AJPFX关于构造器的总结

    构造器        构造器定义        构造器作用        构造器特点        构造器修饰符        默认构造器        构造器重载        构造器和一般函数的区 ...

  7. actuator服务实战

    1. actuator服务实战 1.1. 前言 actuator默认集成了很多端点查看,这里我会挑选也用到可能性大些的 1.2. Endpoints 1.2.1. 使用方式 开启服务后,直接访问:lo ...

  8. 掌握Spark机器学习库-07.14-保序回归算法实现房价预测

    数据集 house.csv 数据集概览 代码 package org.apache.spark.examples.examplesforml import org.apache.spark.ml.cl ...

  9. vim设置默认显示行号

    vim /root/.vimrc 设置在当前登录用户根目录下,.vimrc文件本身不存在,创建后之间添加下面配置保存即可 set number

  10. JavaScript——XMLHttpRequest 家族

    https://www.zhangxinxu.com/wordpress/2013/10/understand-domstring-document-formdata-blob-file-arrayb ...