可以使用栈来做。
#include <iostream>
#include <stack>
using namespace std;
int main(){
int n,ans;
cin>>n;
stack<int> stk;
while(n!=0){
ans=n%2;
n=n/2;
stk.push(ans);
}
while(!stk.empty()){
cout<<stk.top();
stk.pop();
}
return 0;
}
推广到任意进制
#include<iostream>
#include<stack>
#include<cmath>
using namespace std;
void convert(int num,int m){
char c[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
stack<char> s;
int n=abs(num);
while(n){
s.push(c[n%m]);
n/=m;
}
if(num>=0){
while(!s.empty()){
cout<<s.top();
s.pop();
}
}
else{
cout<<"-";
while(!s.empty()){
cout<<s.top();
s.pop();
}
}
}
int main(){
int n,m;
cin>>n>>m;
convert(n,m);
return 0;
}
方法2:
#include <iostream>
#include <cmath>
using namespace std;
char numToChar(int n)
{
if(n<=9&&n>=0)
return n+'0';
if(n>9&&n<16)
return 'A'+(n-10);
return ' ';
}
int main()
{
int num, k;
cin>>num>>k;
string ret="";
int n = abs(num);
while(n)
{
int left = n%k;
ret = numToChar(left)+ ret;
n/=k;
}
if(num<0)
ret = '-'+ret;
cout<<ret<<endl;
return 0;
}