592. 分数加减运算
leetcode-cn.com/problems/fr…
- 正则表达式 正前瞻
exp1(?=exp2):查找 exp2 前面的 exp1。 exp1(?!exp2):查找后面不是 exp2 的 exp1。
- 正则表达式 正后顾
(?<=exp2)exp1:查找 exp2 后面的 exp1。(?<!exp2)exp1:查找前面不是 exp2 的 exp1。
var fractionAddition = function(expression) {
const reg = /[\-\+]?[0-910]+\/[0-910]+/g
const matchs = expression.match(reg)
const numeratorReg = /\*{1}(?=\/)/g
const denominatorReg = /(?<=\/)\*/
const stack = []
let res = matchs[0]
for(let i=0;i<matchs.length;i++){
while(stack.length){
const curr = stack.pop()
res = calcRes(curr,matchs[i])
}
stack.push(res)
}
function calcRes(num1,num2){
let [numerator1,denominator1] = num1.split("\/")
let [numerator2,denominator2] = num2.split("\/")
let denominatorRes = Number(denominator1) * Number(denominator2)
let numeratorRes = Number(numerator1) * Number(denominator2) + Number(numerator2) * Number(denominator1)
let i =2
while(i<= Math.abs(numeratorRes)){
if(numeratorRes % i ===0 && denominatorRes % i ===0){
numeratorRes = numeratorRes/i
denominatorRes = denominatorRes/i
}else{
i++
}
}
if(numeratorRes ==0){
denominatorRes = 1
}
return `${numeratorRes}/${denominatorRes}`
}
return res
};
640. 求解方程
leetcode-cn.com/problems/so…
/**
* @param {string} equation
* @return {string}
*/
var solveEquation = function (equation) {
equation = "+" + equation
let euqaIndex = equation.indexOf("=")
const reverseReg = /[\-\+]/g
let left = equation.slice(0, euqaIndex)
let right = ("+" + equation.slice(euqaIndex + 1)).replace(reverseReg, (match, p1, p2) => {
if (match === "+") return "-"
if (match === "-") return "+"
})
let transEquation = left + right
let patten1 = /[\+\-]{1}[0-9]*x/g
let filteredTransEquation = transEquation.replace(patten1,"")
let sumPatten = /\+[0-9]+/g
let diffPatten = /\-[0-9]+/g
const sumMatch = filteredTransEquation.match(sumPatten) || []
const diffMatch = filteredTransEquation.match(diffPatten) || []
let sum = 0
let sum2 = 0
sumMatch.concat(diffMatch).forEach(num => {
sum = sum + Number(num)
})
const mutiplyMatch = transEquation.match(patten1)
if (mutiplyMatch) {
for (let i = 0
if (mutiplyMatch[i] === "+x") {
sum2++
continue
}
if (mutiplyMatch[i] === "-x") {
sum2--
continue
}
sum2 = Number(mutiplyMatch[i].match(sumPatten)) + Number(mutiplyMatch[i].match(diffPatten)) + sum2
}
}
if (sum2 === 0) {
if (sum === 0) {
return "Infinite solutions"
} else {
return "No solution"
}
}
return "x=" + (-sum / sum2)
};