
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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <ctype.h>
4
5int calculate(char *s) {
6 int length = strlen(s);
7 int stack[length];
8 int top = -1;
9 char sign = '+';
10 int num = 0;
11 for (int i = 0; i < length; i++) {
12 if (isdigit(s[i])) {
13 num = num * 10 + (s[i] - '0');
14 }
15 if ((!isdigit(s[i]) && !isspace(s[i])) || i == length - 1) {
16 if (sign == '+') {
17 stack[++top] = num;
18 } else if (sign == '-') {
19 stack[++top] = -num;
20 } else if (sign == '*') {
21 stack[top] *= num;
22 } else if (sign == '/') {
23 stack[top] /= num;
24 }
25 sign = s[i];
26 num = 0;
27 }
28 }
29
30 int result = 0;
31 while (top != -1) {
32 result += stack[top--];
33 }
34 return result;
35}
36
37int main() {
38 char expression[] = "3+2*2";
39 printf("Output: %d\n", calculate(expression));
40 return 0;
41}This C solution iterates over the string, calculates numeric values, updates the stack with results immediately for '*', '/', while '+' and '-' add or subtract the number to/from the stack respectively. Finally, calculates the sum of values in the stack.
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.
1function
This JavaScript approach processes the expression by altering last computed numbers in-place while tracking only current and last numbers, efficiently managing space and resources.