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. break跳出嵌套循环体

    package com.wh.Object; public class Test { public static void main(String[] args) { // TODO Auto-gen ...

  2. [转]为革命保护视力 --- 给 Visual Studio 换颜色

    本文转自:http://www.cnblogs.com/stg609/p/3723968.html “为革命,保护视力,预防近视,眼保健操开始......” 这个应该是最老版本的眼保健操了,你听过? ...

  3. 关于C# DropDownList 动态加载数据笔记

    今天在处理一个导游注册的页面,其中需要填写地址以及该地址下所有旅行社,地址区级以上都是用下拉列表实现,具体地址街道等手动填写.在填写区县之后,该区县下的所有旅行社也需要动态加载. 后台代码 DataT ...

  4. 2556. [NOIP2016]玩具谜题

    [题目描述] 小南有一套可爱的玩具小人,它们各有不同的职业.有一天,这些玩具小人把小南的眼镜藏了起来.小南发现玩具小人们围成了一个圈,它们有的面朝国内,有的面朝圈外.如下图: 这时singer告诉小南 ...

  5. JWT认证阐述

    哥发达了,是时候实现一下儿时的梦想了,怡红院开起! 店面门脸装修如何?做生意,谁还没个镇店之宝啊?有请我的店长如花小姐! 没事哈!别怕,扭曲的五官往往都藏着一颗纯洁的心灵. 不管如何吧,我的怡红院算是 ...

  6. jquery 序列化form表单

    1.为什么要将form表单序列化? ajax上传form表单的原始方式,是将form表单中所需要的键值对先获取,然后再组装成数据(两种方式:http:localhost:8080/test.do?pe ...

  7. java JDK在windows及mac下安装配置

    windows下安装: JDK下载 地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151. ...

  8. rabiitmq

    Rabbitmq集群高可用 RabbitMQ是用erlang开发的,集群非常方便,因为erlang天生就是一门分布式语言,但其本身并不支持负载均衡. Rabbit模式大概分为以下三种:单一模式.普通模 ...

  9. SQL 索引自动维护计划脚本

    脚本功能: 1,查询数据库中,碎片率在5%以上(官方推荐),有一定数据里的表的索引. 2.如果碎片率在5%<碎片率<=30%  执行重新组织索引.如果在30%以上,执行重建索引 建议在执行 ...

  10. t470安装win7

    终于把win7安装好了,写了个文档 https://files.cnblogs.com/files/cookies9/t470%E5%AE%89%E8%A3%85win7%E6%96%B9%E6%B3 ...