栈+数学运算 | HJ50 四则运算

# 最优解
while True:
    try:
        express = input()
        express.replace("[", "(")
        express.replace("{", "(")
        express.replace("]", ")")
        express.replace("}", ")")
        print(eval(express))
    except:
        break
        

# 我的代码
while True:
    try:
        s = input()
        num_stack = []
        sig_stack = []
        i = 0
        while i < len(s):
            ch = s[i]
            if ch.isdigit():
                j = i+1
                while j<len(s) and s[j].isdigit():
                    j += 1
                num_stack.append(s[i:j])
                i = j
                continue
            elif ch == "+" or ch == "-":  # 运算符为加减时,先看栈中有无乘除
                while sig_stack and sig_stack[-1] in ["*", "/"]:  # 弹出乘除得计算结果,再存入加减运算符
                    num2, num1 = num_stack.pop(), num_stack.pop()
                    new_num = eval(f"{num1}{sig_stack.pop()}{num2}")
                    num_stack.append(new_num)
                if ch == '-':
                    if s[i - 1] not in ['{', '(', '[']:  # 负数前添加'+'运算符,除括号内首数字
                        sig_stack.append('+')
                        num_stack.append(-1)
                        sig_stack.append('*')
                else:
                    sig_stack.append(ch)
            elif ch == "*" or ch == "/":
                sig_stack.append(ch)
            elif ch in ["{", "(", "["]:
                sig_stack.append(ch)
            else:
                sig = sig_stack.pop()
                while sig not in ["{", "(", "["]:
                    num2, num1 = num_stack.pop(), num_stack.pop()
                    new_num = eval(f"{num1}{sig}{num2}")
                    num_stack.append(new_num)
                    sig = sig_stack.pop()
            i += 1
        while sig_stack:
            sig = sig_stack.pop()
            num2, num1 = num_stack.pop(), num_stack.pop()
            new_num = eval(f"{num1}{sig}{num2}")
            num_stack.append(new_num)
        print(int(num_stack[0]))
    except:
        break

用时:2h

华为笔试刷题 文章被收录于专栏

高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107

全部评论

相关推荐

沉淀一会:1.同学你面试评价不错,概率很大,请耐心等待; 2.你的排名比较靠前,不要担心,耐心等待; 3.问题不大,正在审批,不要着急签其他公司,等等我们! 4.预计9月中下旬,安心过节; 5.下周会有结果,请耐心等待下; 6.可能国庆节前后,一有结果我马上通知你; 7.预计10月中旬,再坚持一下; 8.正在走流程,就这两天了; 9.同学,结果我也不知道,你如果查到了也告诉我一声; 10.同学你出线不明朗,建议签其他公司保底! 11.同学你找了哪些公司,我也在找工作。
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务