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
传送门 题目大意 给定一个加减法的表达式,让你任意的添加合法的括号对,使的表达式最大. 题解 考虑到任意左括号一定加在减号右边,那么对于第一个左括号,与该左括号相邻的只含有加号的子序列的贡献一定为负, ...
随机推荐
- 使用ImageMagick处理图片后导致图片变大的问题
最新在使用ImageMagick处理图片时,发现有时经过处理的图片变大的问题. 例如原图为27K,经处理后的图片会变为77K. 先看测试代码: // imgtest.cpp : 定义控制台应用程序的入 ...
- angular.module 参数的意思
定义一个module需要两个参数,第一个作为module的名字,第二个则是指出这个module都依赖哪些别的modules
- JAVA 高级特性 JDBC
需要的jdbc jar 包: mysql-connector-java-5.1.38-b...960.9 KB ojdbc6.jar2.0 MB sqljdbc4.jar455.4 KB 数据持 ...
- ES6学习笔记(2)----变量的解构和赋值
参考书<ECMAScript 6入门>http://es6.ruanyifeng.com/ 变量的解构和赋值 本质上:只要模式匹配,左边的变量就能被赋予右边对应的值 原则: 解构赋值的规则 ...
- 【译】x86程序员手册34-9.7错误代码
9.7 Error Code 错误代码 With exceptions that relate to a specific segment, the processor pushes an error ...
- 未来IT行业的掌控者
(题外话,我发现很多高手都喜欢讲代码实现,喜欢贴代码贴图,我个人不大喜欢这种方式,我觉得最重要的是思想,是想法,具体的实现代码实现步骤由读者自己去实现.这纯属我个人喜好,望各大内高手勿喷,可能是本人水 ...
- 手机信号强度单位:dBm 和 asu
介绍 首先明确:dBm 和 asu 是两个独立的单位,它们的换算关系不唯一. 在 2G 网络下:dBm = -113+2*asu在 4G 网络下:dBm = -140+asu dBm 和 asu 都用 ...
- ALTER SEQUENCE - 更改一个序列生成器的定义
SYNOPSIS ALTER SEQUENCE name [ INCREMENT [ BY ] increment ] [ MINVALUE minvalue | NO MINVALUE ] [ MA ...
- PHP 中 echo 和 print 的区别
一般来说,PHP中动态输出HTML内容,是通过print 和 echo 语句来实现的,在实际使用中, print 和 echo 两者的功能几乎是完全一样.可以这么说,凡是有一个可以使用的地方,另一个也 ...
- 实训day01 python基础
一.编程语言 编程语言:可以被计算机所识别的表达方式. 编程:程序员通过编程语言将自己的想法编写出来,产生的结果就是包含字符的文件. 其中,只有程序在运行时,其中的字符才有特定的语法意义. 二.计算机 ...