
Sponsored
Sponsored
This approach uses a stack to store numbers and consider operator precedence. Multiplication and division are processed immediately, whereas addition and subtraction modify how numbers are pushed onto the stack.
Time Complexity: O(n) where n is the length of the string. Space Complexity: O(n) for storing numbers in the stack.
1using System;
2using System.Collections.Generic;
3
4public class BasicCalculatorII {
5 public int Calculate(string s) {
6 Stack<int> stack = new Stack<int>();
7 char sign = '+';
8 int num = 0;
9 for (int i = 0; i < s.Length; i++) {
10 char c = s[i];
11 if (Char.IsDigit(c)) {
12 num = num * 10 + (c - '0');
13 }
14 if (!Char.IsDigit(c) && c != ' ' || i == s.Length - 1) {
15 if (sign == '+') {
16 stack.Push(num);
17 } else if (sign == '-') {
18 stack.Push(-num);
19 } else if (sign == '*') {
20 stack.Push(stack.Pop() * num);
21 } else if (sign == '/') {
22 stack.Push(stack.Pop() / num);
23 }
24 sign = c;
25 num = 0;
26 }
27 }
28
29 int result = 0;
30 while (stack.Count != 0) {
31 result += stack.Pop();
32 }
33 return result;
34 }
35
36 public static void Main() {
37 BasicCalculatorII calculator = new BasicCalculatorII();
38 Console.WriteLine("Output: " + calculator.Calculate("3+2*2"));
39 }
40}This C# solution iterates over characters, computes numeric values, uses a Stack to handle precedence, immediately processes '*' and '/' operations, appends '+' and '-' directly after converting to proper signs, and computes the final result by accumulating all stack values.
This approach parses the expression twice, first to handle multiplications and divisions, then to process additions and subtractions. This avoids using a stack and simplifies sign handling.
Time Complexity: O(n) where n is the number of characters in the input string. Space Complexity: O(1) since it only uses primitive data types.
1
This Java solution focuses on efficiency by keeping track of only necessary information for computation: current number, last computed number, and current result. It simplifies calculations avoiding extra space usage.