So there is a question on Leetcode to make a basic calculator (It just has operators + and -, and ( and ) brackets). For some reason the code is giving incorrect outputs on Leetcode and an online compiler gives correct outputs with the same test cases. What could be the issue here?
My Code(On Leetcode):
int pos = 0;
int calculate(char *s) {
int sign = 1;
int sum = 0;
int len = strlen(s);
while (pos < len && s[pos] != ')') {
if (s[pos] == '-') {
sign = -1;
printf("-\n");
}
else if (s[pos] == '+') {
sign = 1;
printf("+\n");
}
else if (s[pos] == '(') {
pos++;
sum += sign * calculate(s);
printf("%d\n", sum);
} else {
int a = s[pos] - 48;
if (a >= 0 && a < 10) {
sum = sum + a * sign;
printf("%d\n", sum);
}
}
pos++;
}
return sum;
}
Code on the Compiler (Added a main function to call the function calculate):
// Online C compiler to run C program online
#include <stdio.h>
int pos = 0;
int calculate(char *s) {
int sign = 1;
int sum = 0;
int len = strlen(s);
while (pos < len && s[pos] != ')') {
if (s[pos] == '-') {
sign = -1;
printf("-\n");
}
else if (s[pos] == '+') {
sign = 1;
printf("+\n");
}
else if (s[pos] == '(') {
pos++;
sum += sign * calculate(s);
printf("%d\n", sum);
} else {
int a = s[pos] - 48;
if (a >= 0 && a < 10) {
sum = sum + a * sign;
printf("%d\n", sum);
}
}
pos++;
}
return sum;
}
int main() {
printf("\n\nResult: %d", calculate(" (2-1 + 2 -(2+2))+8"));
return 0;
}
Is it an issue with how Leetcode handles global variables?
The testcases used:
Input: s = "1 + 1"
Input: s = " 2-1 + 2 "
Input: s = "(1+(4+5+2)-3)+(6+8)"
In all these testcases, the online compiler gives accurate outputs, whereas Leetcode gave correct output only for the first
>Solution :
Just a guess:
… it’s very much possible that Leetcode simply calls your function repeatedly rather than starting some program over and over again
–
UnholySheep
I suggest you implement your code without using your global variable; maybe that will eliminate the error.