=======================
s.push()入栈
s.top()取栈顶元素
s.pop()出栈
s.empty()栈不为空
=======================
1.十进制转换成八进制/二进制
#include<iostream>
#include<stack>
//#include"windows.h"
using namespace std;
int main()
{
int n;
stack<int> s;
scanf("%d", &n);
while (n)
{
s.push(n % 8);
n = n / 8;
}
while (!s.empty())
{
printf("%d", s.top());
s.pop();
}
//system("pause");
return 0;
}
主要思想: 建栈->余数入栈->出栈
2.十进制转换成16进制
#include<iostream>
#include<stack>
//#include"windows.h"
using namespace std;
int main()
{
int n;
stack<int> s;
scanf("%d", &n);
while (n)
{
s.push(n % 16);
n = n / 16;
}
while (!s.empty())
{
if (s.top() > 9&&s.top()<16)
{
if (s.top() == 10) printf("A");
if (s.top() == 11) printf("B");
if (s.top() == 12) printf("C");
if (s.top() == 13) printf("D");
if (s.top() == 14) printf("E");
if (s.top() == 15) printf("F");
}
else
printf("%d", s.top());
s.pop();
}
printf("\n");
//system("pause");
return 0;
}
调用c++标准库函数进行进制转换
· sprintf(str,"%d",value)converts to decimal base.
· sprintf(str,"%x",value)converts to hexadecimal base.
· sprintf(str,"%o",value)converts to octal base.
/* itoa example */
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
//#include<windows.h>
using namespace std;
int main()
{
int i;
char buffer[33];
printf("Enter a number: ");
scanf("%d", &i);
itoa(i, buffer, 10);
printf("decimal: %s\n", buffer);
itoa(i, buffer, 16);
printf("hexadecimal小写: %s\n", buffer);
transform(buffer, buffer + strlen(buffer), buffer, toupper);//转大写 toupper:将小写转换成大写,若不是字母,则返回原值
printf("hexadecimal大写: %s\n", buffer);
itoa(i, buffer, 2);
printf("binary: %s\n", buffer);
//system("pause");
return 0;
}