Skip to content
New issue

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

手写题-给加减乘除运算加括号(石墨二面) #17

Open
Rain120 opened this issue Feb 5, 2022 · 0 comments
Open

手写题-给加减乘除运算加括号(石墨二面) #17

Rain120 opened this issue Feb 5, 2022 · 0 comments

Comments

@Rain120
Copy link
Owner

Rain120 commented Feb 5, 2022

现已知一个字符串是由正整数和加减乘除四个运算符(+ - * /)组成。
例如存在字符串 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);
@Rain120 Rain120 changed the title 手写题-给加减乘除运算加括号(石墨) 手写题-给加减乘除运算加括号(石墨二面) Feb 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant