We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
现已知一个字符串是由正整数和加减乘除四个运算符(+ - * /)组成。 例如存在字符串 const str = '11+2-34+5/24+10/5',现在需要将高优先级运算,用小括号包裹起来,例如结果为 '11+2-(34)+(5/24)+(10/5)'。注意可能会出现连续的乘除运算,需要包裹到一起。 请用 javascript 实现这一过程
// 11+2-(3*4)+(5/2*4)+(10/5) cosnt str = '11+2-3*4+5/2*4+10/5'; cosnt addBrackets = (str) => { const res = []; const strArr = str.split(''); let opening = false; let pos = 0; strArr.forEach((item, idx) => { if ('+-*/'.includes(item)) { if ('*/'.includes(item)) { if (!opening) { opening = !opening; for (var i = res.length - 1; i >= 0; i--) { if (!(/\d/.test(res[i]))) { pos = i; break; } } res.splice(pos + 1, 0, '('); } } else { if (opening) { opening = !opening res.push(')') } } res.push(item) } else if (/\d/.test(item)) { res.push(item) } }); if (opening) { res.push(')') } return res.join('') } addBrackets(str);
The text was updated successfully, but these errors were encountered:
No branches or pull requests
The text was updated successfully, but these errors were encountered: