cs106x-lecture9(Autumn 2017)-SPL实现
打卡cs106x(Autumn 2017)-lecture9
(以下皆使用SPL实现,非STL库,后续课程结束会使用STL实现)
1、evaluateMathExpression
Write a recursive function named evaluateMathExpression
that accepts a string parameter representing a math expression on integers and returns the result of that math expression. The expression will consist of single-digit integers and possible operators. All operators will be surrounded by parentheses; we would say that the expression is fully parenthesized. The operators will be either +
or *
. For example, the call of evaluateMathExpression("((1+2)*(3+1)+(1*(2+2)))")
should return xxxx
. You may assume that the string is non-empty and does not contain any other characters.
Constraints: Your code must be recursive and not use any loops. Do not declare any global variables or any auxiliary data structures. You can declare as many primitive variables and strings as you like.
解答:
#include <iostream>
#include <cctype>
#include <string>
#include "console.h"
using namespace std;
int evaluateMathExpressionHelper(const string& exp, int& index) {
if (isdigit(exp[index])) {
return exp[index++] - '0';
} else {
index++;
int left = evaluateMathExpressionHelper(exp, index); // if '(' else 'number'
char op = exp[index++];
int right = evaluateMathExpressionHelper(exp, index);
index++;
if (op == '+') {
return left + right;
} else { // op == '*'
return left * right;
}
}
}
int evaluateMathExpression(string exp) {
int index = 0;
return evaluateMathExpressionHelper(exp, index);
}
int main() {
cout << evaluateMathExpression("(2+3)") << endl; // 5
cout << evaluateMathExpression("((2+3)*(1+1))") << endl; // 10
cout << evaluateMathExpression("(((1+2)*(3+1))+(1*(2+2)))") << endl; // 16
cout << evaluateMathExpression("(((3*(1+(2+1)))+((9+2)*4))*((1+1)+(2+(2+2))))") << endl; // 448
cout << evaluateMathExpression("8") << endl; // 8
return 0;
}
2、evenDigits
Write a recursive function named evenDigits
that accepts an integer parameter n and returns a new integer containing only the even digits from n, in the same order. If n does not contain any even digits, return 0.
For example, the call of evenDigits(8342116)
should return 8426
and the call of evenDigits(35179)
should return 0
.
解答:
#include <iostream>
#include <string>
#include "console.h"
using namespace std;
int evenDigitsHelper(int n, int& t) {
if (n < 10) {
if (n % 2 == 0) {
n *= t;
t *= 10;
return n;
} else {
return 0;
}
} else {
return evenDigitsHelper(n % 10, t) + evenDigitsHelper(n / 10, t);
}
}
int evenDigits(int n) {
int t = 1;
if (n >= 0) {
return evenDigitsHelper(n, t);
} else {
return -evenDigitsHelper(-n, t);
}
}
int main() {
cout << evenDigits(8342116) << endl; // 8426
cout << evenDigits(40109) << endl; // 400
cout << evenDigits(8) << endl; // 8
cout << evenDigits(-163505) << endl; // -60
cout << evenDigits(35179) << endl; // 0
cout << evenDigits(-2) << endl; // -2
cout << evenDigits(0) << endl; // 0
return 0;
}