栈+数学运算 | 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

全部评论

相关推荐

头像
11-05 09:57
已编辑
天津大学 Java
中兴 小ssp做c++ 薪资待遇得订到15级
点赞 评论 收藏
分享
hso_:哈哈哈哈哈哈我没offer一样在同一道题开喷了
投递深圳同为数码等公司10个岗位
点赞 评论 收藏
分享
我冲冲冲冲冲:泪目了,好想选自己想选的答案啊
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务