算法训练营第二十一天| 基本计算器 II
1.题目链接https://leetcode.cn/problems/basic-calculator-ii/description/ 优秀题解https://leetcode.cn/problems/basic-calculator-ii/solutions/91271/chai-jie-fu-za-wen-ti-shi-xian-yi-ge-wan-zheng-ji-/2.#include stdio.h #include stdlib.h #include ctype.h #include string.h int calculate(char* s) { int stackSize 4; int* stack (int*)malloc(stackSize * sizeof(int)); int top -1; int num 0; char op ; int len strlen(s); for (int i 0; i len; i) { if (isdigit(s[i])) { num num * 10 (s[i] - 0); } if ((!isdigit(s[i]) s[i] ! ) || i len - 1) { if (top 1 stackSize) { stackSize * 2; stack (int*)realloc(stack, stackSize * sizeof(int)); } switch (op) { case : stack[top] num; break; case -: stack[top] -num; break; case *: stack[top] * num; break; case /: stack[top] stack[top] / num; break; } op s[i]; num 0; } } int result 0; for (int j 0; j top; j) { result stack[j]; } free(stack); return result; }
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2571502.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!