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 d66e733

Browse files
committed
添加 0150.逆波兰表达式求值.md C 版本
1 parent d6f7f3a commit d66e733

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

‎problems/0150.逆波兰表达式求值.md‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,67 @@ impl Solution {
502502
}
503503
```
504504

505+
### C:
506+
507+
```c
508+
int str_to_int(char *str) {
509+
// string转integer
510+
int num = 0, tens = 1;
511+
for (int i = strlen(str) - 1; i >= 0; i--) {
512+
if (str[i] == '-') {
513+
num *= -1;
514+
break;
515+
}
516+
num += (str[i] - '0') * tens;
517+
tens *= 10;
518+
}
519+
return num;
520+
}
521+
522+
int evalRPN(char** tokens, int tokensSize) {
523+
524+
int *stack = (int *)malloc(tokensSize * sizeof(int));
525+
assert(stack);
526+
int stackTop = 0;
527+
528+
for (int i = 0; i < tokensSize; i++) {
529+
char symbol = (tokens[i])[0];
530+
if (symbol < '0' && (tokens[i])[1] == '0円') {
531+
532+
// pop两个数字
533+
int num1 = stack[--stackTop];
534+
int num2 = stack[--stackTop];
535+
536+
// 计算结果
537+
int result;
538+
if (symbol == '+') {
539+
result = num1 + num2;
540+
} else if (symbol == '-') {
541+
result = num2 - num1;
542+
} else if (symbol == '/') {
543+
result = num2 / num1;
544+
} else {
545+
result = num1 * num2;
546+
}
547+
548+
// push回stack
549+
stack[stackTop++] = result;
550+
551+
} else {
552+
553+
// push数字进stack
554+
int num = str_to_int(tokens[i]);
555+
stack[stackTop++] = num;
556+
557+
}
558+
}
559+
560+
int result = stack[0];
561+
free(stack);
562+
return result;
563+
}
564+
```
565+
505566
<p align="center">
506567
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
507568
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
(0)

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