File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff 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"/>
You can’t perform that action at this time.
0 commit comments