Stack.h的源码懒得发了,直接上实现#include <iostream>
#include "d:\My Documents\DEV-C++\Stack\Stack.h"
unsigned int func(unsigned int n);
int main()
{
using std::cout;
using std::endl;
using std::cin;
cout << "请输入一个数字: ";
unsigned int num;
cin >> num;
Stack<unsigned int> f(10);
f.Push(num);
while (num != 0) // 保存num的值
{
num /= 2;
f.Push(num);
}
f.Pop(num); // 去除栈顶的0
unsigned int result = 1;
while (!f.Is_Empty()) // 模拟递归操作
{
f.Pop(num); // 模拟递归回溯(返回)
result *= num;
}
cout << "非递归得到f(n) = " << result << endl; // 最后result就是最后的结果
cout << "递归得到f(n) = " << func(num) << endl; // 此时num等于第一个输入的数字
return 0;
}
unsigned int func(unsigned int n)
{
if (n == 0)
return 1;
return n * func(n / 2);
}
|