#include<bits/stdc++.h>
using namespace std;
int main(){
int x;
cout << "Ingrese numeros, 0 para terminar:" << endl;
cin >> x;
while (x != 0){
vector<int> v;
while(x > 0){
v.push_back(x % 2); // Almaceno los restos en una pila
x = x / 2; // Reduzco x
}
for (int i = (v.size() - 1); i >= 0; i--) // Imprimo los numeros de atras para delante
cout << v[i];
cout << endl;
cout << "Ingrese numeros, 0 para terminar:" << endl;
cin >> x;
}
return 0;
}
我希望这有帮助:
虽然这个答案已经得到回答,但我贡献了我的一粒沙子:
选项 1:简化其他提议的解决方案
选项 2:使用位集
如果您只想打印它,我建议您使用以下递归算法,它不仅可以将您从十进制转换为二进制,还可以转换为任何基数。如果基数大于 10,您将不得不进行一些调整,但它是最小的。它是这样的:
我就是这样做的