# 2966. 二进制与十六进制

### include

using namespace std;
int T,n;
vector tmp;
void print_Binary(int aa)
{
if(aa==0)
{
cout<<‘0’;
return;
}
tmp.clear();
while(aa)
{
tmp.push_back(aa%2);
aa/=2;
}
for(int i=tmp.size()-1;i>=0;i–) cout<>T;
for(int step=0;step>n;
printf(“case #%d:\n”,step);
print_Binary(n);
printf(” %X\n”,n);
}
return 0;
}

1.直接输出八进制%o

%03x

2.像输出二进制里面用到了while(aa)

3.这里输出二进制要把结果逆转，可以用递归的方法，但为了防止栈溢出，一般不那么干

0要特殊判断

### include

using namespace std;
int main()
{
int t;
int count = 0;
cin >> t;
while (t–) {
int num;
cin >> num;
int temp1 = num, temp2 = num;
stack q;
cout << “case #” << count++ << “:” << endl;
if (!num) {
cout << “0 0” << endl;
continue;
}
while (temp1) {
int k = temp1 % 2;
q.push(k);
temp1 /= 2;
}
while (!q.empty()) {
int k = q.top();
cout << k;
q.pop();
}
cout << ” “;
while (temp2) {
int k = temp2 % 16;
q.push(k);
temp2 /= 16;
}
while (!q.empty()) {
int k = q.top();
if (k > 9) {
char ch = k + 55;
cout << ch;
}
else
cout << k;
q.pop();
}
if (t == 0)
break;
cout << endl;
}
return 0;
}

1. 0要特判
2. 直接用了STL里的stack，运行速度上可能会慢一点
#include <bits/stdc++.h>
using namespace std;
//use stack to realize

int T,cnt;
stack<int> getBinary(int n)
{
stack<int> myStack1;
if(n==0) myStack1.push(0);//judging 0 is important
while(n!=0){
int temp=n%2;
myStack1.push(temp);
n/=2;
}
return myStack1;
}

{
stack<char> myStack2;
char ch[16];
for(int i=0;i<16;++i){
if(i<10) ch[i]=i+'0';
else ch[i]='A'+i-10;
}
if(n==0) myStack2.push('0');
while(n!=0)
{
int temp=n%16;
myStack2.push(ch[temp]);
n/=16;
}
return myStack2;
}
int main()
{
cin>>T;
int n;
while(T--){
cin>>n;
stack<int> myStack1=getBinary(n);
printf("case #%d:\n",cnt++);
while(!myStack1.empty()){
cout<<myStack1.top();
myStack1.pop();
}
cout<<' ';
while(!myStack2.empty()){
cout<<myStack2.top();
myStack2.pop();
}
cout<<endl;
}
return 0;
}