如需转载,请标明 出处。
十进制转二进制的几种解法:
十进制转二进制的时候的瓶颈是短除法之后的逆序;
解法一:利用递归
#include<iostream>
using namespace std;
void f(int n)
{
if (n > 0)
{
f(n / 2);
cout << n % 2;
}
}
int main()
{
int n;
cout << "请输入一个整数:" << endl;
cin >> n;
f(n);
return 0;
}
解法二:利用数组
#include<iostream>
using namespace std;
int main()
{
int s[100];
int count=0,n;
cout << "请输入一个正整数:" << endl;
cin >> n;
while (n != 0)
{
s[++count] = n % 2;
n = n / 2;
}
for (; count > 0; count--)
{
cout << s[count];
}
return 0;
}
解法三:利用栈
#include<iostream>
#include<stack>
using namespace std;
stack<int>STD;
int main()
{
int n;
cout << "请输入一个正整数:" << endl;
cin >> n;
while (n != 0)
{
STD.push(n % 2);
n = n / 2;
}
while (!STD.empty())
{
cout << STD.top();
STD.pop();
}
return 0;
}