daily pastebin goal
47%
SHARE
TWEET

Untitled

a guest Oct 19th, 2018 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <cstdio>
  2. #include <ctype.h>
  3.  
  4. int token;
  5.  
  6. int expr();
  7. int number();
  8. int digit();
  9. int term();
  10. int factor();
  11.  
  12. void getToken() {
  13.     token = getchar();
  14. }
  15.  
  16. int expr() {
  17.     int result = term();
  18.     while (token == '+' || token == '-') {
  19.         if (token == '+') {
  20.             getToken();
  21.             result += term();
  22.         }
  23.         else {
  24.             getToken();
  25.             result -= term();
  26.         }
  27.     }
  28.     if (token == ')')
  29.         getToken();
  30.     return result;
  31. }
  32.  
  33. int term() {
  34.     int result = factor();
  35.     while (token == '*' || token=='/') {
  36.         if (token == '*') {
  37.             getToken();
  38.             result *= factor();
  39.         }
  40.         else {
  41.             getToken();
  42.             result /= factor();
  43.         }
  44.     }
  45.     return result;
  46. }
  47.  
  48. int factor() {
  49.     if (token == '(') {
  50.         getToken();
  51.         return expr();
  52.     }
  53.     return number();
  54. }
  55.  
  56. int digit() {
  57.     int result;
  58.     if (isdigit(token)) {
  59.         result = token - '0';
  60.         getToken();
  61.     }
  62.     return result;
  63. }
  64.  
  65. int number() {
  66.     int result = 0;
  67.     while (isdigit(token)) {
  68.         result = 10 * result + digit();
  69.     }
  70.     return result;
  71. }
  72.  
  73. int main() {
  74.     getToken();
  75.     printf("%d", expr());
  76.     return 0;
  77. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top