题目描述
解析加减法运算
 如:
 输入字符串:"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])
      

京公网安备 11010502036488号