What is the function of a basic calculator in mathematics?

2026-06-05 12:135阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计298个文字,预计阅读时间需要2分钟。

What is the function of a basic calculator in mathematics?

实现一个基本的计算器,用于评估一个简单的表达式字符串。该表达式字符串只包含非负整数、+、-、*、/运算符和空格。整数除法应截断为零。例如:输入:3 + 2

Implement a basic calculator to evaluate a simple expression string.

The expression string contains onlynon-negativeintegers,+,-,*,/operators and empty spaces. The integer division should truncate toward zero.

Example 1:

Input: "3+2*2" Output: 7

Example 2:

Input: " 3/2 " Output: 1

Example 3:

What is the function of a basic calculator in mathematics?

Input: " 3+5 / 2 " Output: 5

Note:

  • You may assume that the given expression is always valid.
  • Do notuse theevalbuilt-in library function.

Approach #1: Stack. [Java]

class Solution { public int calculate(String s) { if (s == null || s.length() == 0) return 0; Stack<Integer> stack = new Stack(); s += ‘+‘; char op = ‘+‘; for (int i = 0, n = 0; i < s.length(); ++i) { char c = s.charAt(i); if (c >= ‘0‘ && c <= ‘9‘) { n = n * 10 + c - ‘0‘; continue; } if (c == ‘ ‘) continue; if (op == ‘+‘) stack.push(n); else if (op == ‘-‘) stack.push(-n); else if (op == ‘*‘) stack.push(stack.pop() * n); else if (op == ‘/‘) stack.push(stack.pop() / n); op = c; n = 0; } int ret = 0; while (!stack.empty()) ret += stack.pop(); return ret; } }

本文共计298个文字,预计阅读时间需要2分钟。

What is the function of a basic calculator in mathematics?

实现一个基本的计算器,用于评估一个简单的表达式字符串。该表达式字符串只包含非负整数、+、-、*、/运算符和空格。整数除法应截断为零。例如:输入:3 + 2

Implement a basic calculator to evaluate a simple expression string.

The expression string contains onlynon-negativeintegers,+,-,*,/operators and empty spaces. The integer division should truncate toward zero.

Example 1:

Input: "3+2*2" Output: 7

Example 2:

Input: " 3/2 " Output: 1

Example 3:

What is the function of a basic calculator in mathematics?

Input: " 3+5 / 2 " Output: 5

Note:

  • You may assume that the given expression is always valid.
  • Do notuse theevalbuilt-in library function.

Approach #1: Stack. [Java]

class Solution { public int calculate(String s) { if (s == null || s.length() == 0) return 0; Stack<Integer> stack = new Stack(); s += ‘+‘; char op = ‘+‘; for (int i = 0, n = 0; i < s.length(); ++i) { char c = s.charAt(i); if (c >= ‘0‘ && c <= ‘9‘) { n = n * 10 + c - ‘0‘; continue; } if (c == ‘ ‘) continue; if (op == ‘+‘) stack.push(n); else if (op == ‘-‘) stack.push(-n); else if (op == ‘*‘) stack.push(stack.pop() * n); else if (op == ‘/‘) stack.push(stack.pop() / n); op = c; n = 0; } int ret = 0; while (!stack.empty()) ret += stack.pop(); return ret; } }