昨天看到严蔚敏数据结构的书上将到了栈的一个应用,就是实现进制的转换
比如:
(1348)10--
N N/8 N%8
1348 168 4
168 21 0
21 2 5
2 0 2
所以
(1348)10-->(2504)8
具体代码如下:
// UseStack.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int n=1348;
stack<int> T;
while(n)
{
T.push(n%8);
n/=8;
}
while(!T.empty())
{
int result =0;
result=T.top();
cout<<result;
T.pop();
}
system("pause");
return 0;
}
以上代码只是将栈中数字打印出来,并没有返回一个数字,那么我现在就想该函数有个返回值,显然这个得到最后计算结果的算法思想和"123"-->123的思想是一样的,所以我写了以下代码,实现了返回结果的功能:
代码如下
// 10To8--01.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;
int TenTo8(int n)
{
int result=0;
stack<int> T;
while (n)
{
T.push(n%8);
n/=8;
}
while(!T.empty())
{
int num=T.top();
//cout<<num; 直接将栈中的元素打印出来
//给该函数返回一个结果
result=result*10+num;
T.pop();
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<TenTo8(1348)<<endl;
system("pause");
return 0;
}