592. Fraction Addition and Subtraction
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:
- The input string only contains
'0'
to'9'
,'/'
,'+'
and'-'
. So does the output. - Each fraction (input and output) has format
±numerator/denominator
. If the first input fraction or the output is positive, then'+'
will be omitted. - 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.
- The number of given fractions will be in the range [1,10].
- 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的更多相关文章
- 【LeetCode】592. Fraction Addition and Subtraction 解题报告(Python)
[LeetCode]592. Fraction Addition and Subtraction 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuem ...
- [LeetCode] 592. Fraction Addition and Subtraction 分数加减法
Given a string representing an expression of fraction addition and subtraction, you need to return t ...
- LC 592. Fraction Addition and Subtraction
Given a string representing an expression of fraction addition and subtraction, you need to return t ...
- 【leetcode】592. Fraction Addition and Subtraction
题目如下: 解题思路:本题考察的是分数的加减法.小学时候就学过,分数的加减法是先求两个分母的最小公倍数,然后分子分别乘以最小公倍数与自己分母的商,相加后约分即可.所以,本题只要按+,-两个符号分割输入 ...
- [LeetCode] Fraction Addition and Subtraction 分数加减法
Given a string representing an expression of fraction addition and subtraction, you need to return t ...
- [Swift]LeetCode592. 分数加减运算 | Fraction Addition and Subtraction
Given a string representing an expression of fraction addition and subtraction, you need to return t ...
- [leetcode-592-Fraction Addition and Subtraction]
Given a string representing an expression of fraction addition and subtraction, you need to return t ...
- 大数据加减(Big data addition and subtraction)
题目描述 Description 加减法是计算中的基础运算,虽然规则简单,但是位数太多了,也难免会出错.现在的问题是:给定任意位数(不超过1000位)的加减法算式,请给出正确结果.为提高速度,保证给定 ...
- Arc066_E Addition and Subtraction Hard
传送门 题目大意 给定一个加减法的表达式,让你任意的添加合法的括号对,使的表达式最大. 题解 考虑到任意左括号一定加在减号右边,那么对于第一个左括号,与该左括号相邻的只含有加号的子序列的贡献一定为负, ...
随机推荐
- Wannafly挑战赛10:A题:小H和迷宫
题目描述 小H陷入了一个迷宫中,迷宫里有一个可怕的怪兽,血量有N点,小H有三瓶魔法药水,分别可以使怪兽损失a%.b%.c%的血量(之后怪兽的血量会向下取整),小H想合理地运用这三瓶药水,使 ...
- Service官方教程(10)Bound Service的生命周期函数
Managing the Lifecycle of a Bound Service When a service is unbound from all clients, the Android sy ...
- java实现九九乘法表
public class Demo { public static void main(String[] args) { for (int i = 1; i < 10; i++) { ...
- 基于Windows7下snort+apache+php 7 + acid(或者base) + adodb + jpgraph的入侵检测系统的搭建(图文详解)(博主推荐)
为什么,要写这篇论文? 是因为,目前科研的我,正值研三,致力于网络安全.大数据.机器学习.人工智能.区域链研究领域! 论文方向的需要,同时不局限于真实物理环境机器实验室的攻防环境.也不局限于真实物理机 ...
- [转]探索 Windows Azure Storage
本文转自:https://msdn.microsoft.com/zh-tw/jj573842 概觀 儲存服務 (Storage services) 在 Windows Azure 運算模擬器中提供了可 ...
- mac重启iterm后不会自动加载.bash_profile
我用的zsh,由于平时设置的环境变量都是在.bash_profile文件中,每次重启iterm后,都需要重启手动加载.bash_profile文件,很麻烦. 设置自动加载.bash_profile的方 ...
- 浏览器和ES5的介绍
浏览器的组成 : shell(浏览器的外壳).内核(渲染引擎.js引擎)主流浏览器及其内核: IE tritent(IE9及以下,IE10及以上用webkit) ...
- json三层解析(数组解析)
里面多了数组,所以用到了JOSNArray package com.xykj.weather; import java.io.BufferedReader; import java.io.IOExce ...
- IIS HTTP 错误 401.3的解决办法
目标网站添加新用户Everyone,选上需要的Everyone用户权限
- notepad++新建文档时,会出现语法错误的红色下波浪线
notepad++新建文档时,会出现语法错误的红色下波浪线: 原因:新建文档时默认设置语言为PHP. 解决方法:修改默认语言为java或JavaScript,如下: 小结:打开文档时,也可能出现下波浪 ...