自己拿个栈算阶乘
下面用 vector 当栈,模拟阶乘递归的「往下压、往回乘」。运行下面这段程序:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<int> st;
for (int n = 5; n >= 1; n--) st.push_back(n); // 往下:把每一层要乘的数压进去
long long r = 1;
while (!st.empty()) { // 往回:一层层弹出来乘
r *= st.back();
st.pop_back();
}
cout << r << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)