1. 问题描述
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
Note: Do not use the eval built-in library function.
Tags:String
Similar Problems:(H)Basic Calculator、(H)Expression Add Operators
Solution:
class Solution { public: int calculate(string s) { } };
2. 解答思路
2.1 合法性判断
- 空字符串
- 在第一个数字字符(‘0‘~‘9‘)出现前(假设在位置i),则位置0到位置i的字符只能为空格‘ ’或一个正负号‘+’或‘-’号
- 除数字、加、减、乘、除、空格字符外,其他字符均为非法字符,返回0。同时,需设置全局标志位,与计算结果为0进行区分
- 有没有可能多个运算符字符相邻?e.g. "- + /"、“*/-” etc. 不会,因为题目中说You may assume that the given expression is always valid.
- 若有溢出如何处理
2.2 整数提取
- 如何从相邻的多个空格与数字字符的串中,提取出整数
2.3 算法
3. 代码
发
4. 反思
发
时间: 2024-10-29 19:10:31