fork download
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. char const *
  5. calculate( char const * input,
  6. int * value )
  7. {
  8. char ch = *input;
  9.  
  10. if( isdigit(ch) ) {
  11. *value = ch - '0';
  12. return input + 1;
  13. }
  14.  
  15. int left, right;
  16. input = calculate( input+1, &left );
  17. input = calculate( input, &right );
  18.  
  19. switch( ch ) {
  20. case '+':
  21. *value = left + right;
  22. break;
  23. case '-':
  24. *value = left - right;
  25. break;
  26. case '*':
  27. *value = left * right;
  28. break;
  29. case '/':
  30. *value = left / right;
  31. break;
  32. default:
  33. // should not reach here
  34. break;
  35. }
  36.  
  37. return input;
  38. }
  39.  
  40.  
  41. int main() {
  42.  
  43. char const * input = "+1+*23*45";
  44. int result;
  45.  
  46. calculate( input, &result );
  47.  
  48. printf( "result is : %d\n", result );
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0.01s 1676KB
stdin
Standard input is empty
stdout
result is : 27