Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bda342c

Browse files
Improvement
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent a01d82f commit bda342c

File tree

1 file changed

+51
-46
lines changed

1 file changed

+51
-46
lines changed

‎0224_basic_calculator/calculator.c‎

Lines changed: 51 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,65 @@
1+
#include <ctype.h>
12
#include <stdio.h>
23
#include <stdlib.h>
34

4-
static int calculator(char *s)
5+
6+
static int dfs(char **input)
57
{
6-
int n;
7-
int pos1 = 0;
8-
int pos2 = 0;
9-
int*nums = malloc(1000*sizeof(int));
10-
char *signs = malloc(1000*sizeof(char));
8+
int i, res=0;
9+
int num = 0;
10+
int stk[700], pos = 0;
11+
charsign = '+';
12+
char *s = *input;
1113

12-
nums[pos1++] = 0;
1314
while (*s != '0円') {
14-
switch (*s) {
15-
case '+':
16-
case '-':
17-
case '(':
18-
signs[pos2++] = *s;
19-
break;
20-
case ')':
21-
--pos2;
22-
if (pos1 >= 2 && pos2 > 0 && signs[pos2 - 1] != '(') {
23-
n = nums[--pos1];
24-
int a = nums[--pos1];
25-
if (signs[--pos2] == '+') {
26-
n = a + n;
27-
} else {
28-
n = a - n;
29-
}
30-
}
31-
nums[pos1++] = n;
32-
break;
33-
case ' ':
34-
break;
35-
default:
36-
n = 0;
37-
while(*s >= '0' && *s <= '9') {
38-
n = n * 10 + (*s - '0');
39-
s++;
40-
}
41-
s--;
15+
char c = *s++;
16+
if (isdigit(c)) {
17+
num = 10 * num + (c - '0');
18+
}
19+
20+
if (c == '(') {
21+
/* dfs("2*(1+3)") = 2 * dfs("1+3") */
22+
num = dfs(&s);
23+
}
4224

43-
if (pos1 >= 2 && signs[pos2 - 1] != '(' && signs[pos2 - 1] != '(') {
44-
int a = nums[--pos1];
45-
if (signs[--pos2] == '+') {
46-
n = a + n;
47-
} else {
48-
n = a - n;
49-
}
25+
if (!isdigit(c) && c != ' ' || *s == '0円') {
26+
switch (sign) {
27+
case '+':
28+
stk[pos++] = num;
29+
break;
30+
case '-':
31+
stk[pos++] = -num;
32+
break;
33+
case '*':
34+
stk[pos - 1] *= num;
35+
break;
36+
case '/':
37+
stk[pos - 1] /= num;
38+
break;
5039
}
51-
nums[pos1++] = n;
52-
break;
40+
/* update the sign and reset the number */
41+
sign = c;
42+
num = 0;
5343
}
54-
s++;
44+
45+
/* return from the dfs */
46+
if (c == ')')
47+
break;
48+
}
49+
50+
/* update position */
51+
*input = s;
52+
53+
while (pos > 0) {
54+
res += stk[--pos];
5555
}
5656

57-
return n;
57+
return res;
58+
}
59+
60+
static int calculator(char *s)
61+
{
62+
return dfs(&s);
5863
}
5964

6065
int main(int argc, char **argv)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /