Created
September 19, 2012 23:41
-
-
Save rockuw/3753057 to your computer and use it in GitHub Desktop.
amazon online test 2
This file contains 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 <stdlib.h> | |
#include <string.h> | |
#define MAX_INPUT_SIZE 100 | |
int g_error = 0; | |
void error(const char *msg){ | |
/* | |
printf("%s\n", msg); | |
exit(-1); | |
*/ | |
g_error = 1; | |
} | |
int str_to_int(char str[], int begin, int end){ | |
int result = 0, i, sign = 1; | |
i = begin; | |
if(str[begin] == '+') i ++; | |
if(str[begin] == '-') { sign = -1; i ++; } | |
for(; i <= end; i ++){ | |
result *= 10; | |
result += str[i] - '0'; | |
} | |
return sign * result; | |
} | |
void op_result(char op, double *result, double a){ | |
if(op == '+'){ | |
*result = *result + a; | |
} else if(op == '-'){ | |
*result = *result - a; | |
} else if(op == '*'){ | |
*result = *result * a; | |
} else if(op == '/'){ | |
*result = *result / a; | |
} else { | |
error("invalid operator"); | |
} | |
} | |
int cal(char str[], int begin, int end){ | |
double result = 0; | |
char op; | |
int i, j, p_count, is_first; | |
if(str[begin] == '+' || str[begin] == '-' || (str[begin] >= '0' && str[begin] <= '9')){ | |
return str_to_int(str, begin, end); | |
} else if(str[begin] == '('){ | |
is_first = 1; | |
op = str[begin+1]; | |
i = begin + 2; | |
for(j = i + 1; j < end; j ++){ | |
while(str[i] == ' ') i ++; | |
/* sub structure */ | |
if(str[i] == '('){ | |
p_count = 1; | |
for(j = i+1; j <= end; j ++){ | |
if(str[j] == ')') p_count --; | |
if(str[j] == '(') p_count ++; | |
if(p_count == 0) { j ++; break; } | |
} | |
} else { | |
/* simple case */ | |
for(j = i+1; j <= end; j ++){ | |
if(str[j] == ' ' || str[j] == ')') break; | |
} | |
} | |
if(is_first){ | |
result = cal(str, i, j - 1); | |
is_first = 0; | |
} else { | |
op_result(op, &result, cal(str, i, j - 1)); | |
} | |
i = j + 1; | |
} | |
} else{ | |
error("invalid begin char"); | |
} | |
return result; | |
} | |
int main(){ | |
char str[MAX_INPUT_SIZE]; | |
int result; | |
fgets(str, MAX_INPUT_SIZE, stdin); | |
/* remove the trailing \n */ | |
str[strlen(str) - 1] = 0; | |
result = cal(str, 0, strlen(str) - 1); | |
if(g_error){ | |
printf("Syntax Error.\n"); | |
} else { | |
printf("%d\n", result); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment