【2019校招真题】解析加减法运算(python)

题目描述

解析加减法运算
如:
输入字符串:"1+2+3" 输出:"6"
输入字符串:"1+2-3" 输出:"0"
输入字符串:"-1+2+3" 输出:"4"
输入字符串:"1" 输出:"1"
输入字符串:"-1" 输出:"-1"

已知条件:输入的运算都是整数运算,且只有加减运算

要求:输出为String类型,不能使用内建的eval()函数

输入描述:

输入字符串:"1+2+3"

输出描述:

输出:"6"

示例1

输入

1+2+3

输出

6

解题思路

用两个数组分别存储操作数和操作符,对加减运算表达式进行解析。

主要难题:

1、需要考虑当减号位于表达式第一个位置的情况,此时减号的作用为负号:

  if i == 0 and s[i] == '-':
    i += 1
    temp = ''
    while i < len(s) and s[i] >= '0' and s[i] <= '9':
      temp += s[i]
      i += 1
    nums.append(-1 * int(temp))

2、 数字的长度可能是多位的,需要对数字进行拼接:

temp = ''
    while i < len(s) and s[i] >= '0' and s[i] <= '9':
      temp += s[i]
      i += 1
    nums.append(-1 * int(temp))

完整代码

import sys
s = sys.stdin.readline().strip()
nums = []
op = []
i = 0
while i < len(s):
  if i == 0 and s[i] == '-':
    i += 1
    temp = ''
    while i < len(s) and s[i] >= '0' and s[i] <= '9':
      temp += s[i]
      i += 1
    nums.append(-1 * int(temp))
  else:
    if s[i] == '-' or s[i] == '+':
      op.append(s[i])
      i += 1
    else:
      temp = ''
      while i < len(s) and  s[i] >= '0' and s[i] <= '9':
        temp += s[i]
        i += 1
      nums.append(int(temp))
      if len(nums) == 2:
        t = 0
        if op[0] == '+':
          t = nums[0] + nums[1]
        elif op[0] == '-':
          t = nums[0] - nums[1]
        nums.pop()
        nums.pop()
        op.pop()
        nums.append(t)
print(nums[0])
    

 

全部评论

相关推荐

07-02 13:52
武汉大学 golang
骗你的不露头也秒
牛客87776816...:😃查看图片
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-04 18:02
好不容易拿到了字节Offer,鼠鼠做后端的,但家里人觉得可能被裁员不稳定,让鼠鼠去投国企,现在好纠结到底该咋选
文档传偷助手:该投就投吧,不过建议别放弃offer 拿到手里的才是最好的
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
05-30 12:03
山西大学 C++
offer来了我跪着...:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务