天天看點

十進制轉二進制的幾種解法(c++)

如需轉載,請标明 出處。

十進制轉二進制的幾種解法:

十進制轉二進制的時候的瓶頸是短除法之後的逆序;

解法一:利用遞歸

#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;
}