Last active
October 8, 2017 14:43
-
-
Save sat0b/3049603ca6d1fc9d0e3725c3bb9b8499 to your computer and use it in GitHub Desktop.
逆ポーランド記法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <ctype.h> | |
| #include <stdlib.h> | |
| int main(int argc, char *argv[]) { | |
| if (argc != 2) { | |
| fprintf(stderr, "Usage %s equation\n", argv[0]); | |
| exit(1); | |
| } | |
| char stack[256] = {'\0'}; | |
| int sp = -1; | |
| for (char *p = argv[1]; *p; p++) { | |
| switch(*p) { | |
| case ' ': | |
| case '\t': | |
| case '\r': | |
| case '\n': | |
| break; | |
| case '+': | |
| case '-': | |
| for (; stack[sp] == '*' || stack[sp] == '/'; sp--) | |
| printf("%c ", stack[sp]); | |
| stack[++sp] = *p; | |
| break; | |
| case '*': | |
| case '/': | |
| stack[++sp] = *p; | |
| break; | |
| case '(': | |
| stack[++sp] = *p; | |
| break; | |
| case ')': | |
| for (; stack[sp] != '('; sp--) | |
| printf("%c ", stack[sp]); | |
| sp--; | |
| break; | |
| default: | |
| if (isdigit(*p)) { | |
| printf("%c ", *p); | |
| } | |
| } | |
| } | |
| stack[++sp] = '\0'; | |
| for (; sp >= 0; sp--) { | |
| printf("%c ", stack[sp]); | |
| } | |
| puts(""); | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <string.h> | |
| #include <stdlib.h> | |
| #include <ctype.h> | |
| int main(int argc, char *argv[]) { | |
| if (argc != 2) { | |
| fprintf(stderr, "Usage %s rpn_equation\n", argv[0]); | |
| exit(1); | |
| } | |
| int stack[256] = {0}; | |
| int sp = 0; | |
| for (char *p = argv[1]; *p; p++) { | |
| if (isdigit(*p)) { | |
| stack[++sp] = *p - '0'; | |
| } else if (strchr("+-*/", *p)) { | |
| char op = *p; | |
| int y = stack[sp--]; | |
| int x = stack[sp--]; | |
| switch(op) { | |
| case '+': | |
| stack[++sp] = x + y; | |
| break; | |
| case '-': | |
| stack[++sp] = x - y; | |
| break; | |
| case '*': | |
| stack[++sp] = x * y; | |
| break; | |
| case '/': | |
| stack[++sp] = x / y; | |
| break; | |
| } | |
| } | |
| } | |
| printf("%d\n", stack[sp]); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment