#include <iostream>
using namespace std;
// 前置条件: n >= 0
// 后置条件: 输出n的二进制等值数
// (递归版本--优于迭代版本)
// worstTime(n) 是 O(log n).
void writebinary1(int n)
{
if (n == 0 || n == 1)
cout << n;
else{
writebinary1(n/2);
cout << n%2;
}
}
// (迭代版本)
// 描述:用一个while循环生成位的值,并用一个数组保存这些值,
// 然后是一个反序步骤的for循环输出那些值。
// worstTime(n) 是 O(n).
void writebinary2(int n)
{
int i = 0, bin[32];
if (n == 0 || n == 1){
bin[0] = n;
i++;
}
while (n != 1 && n != 0){
bin[i] = n % 2;
i++;
n = n / 2;
}
bin[i] = n;
for (int j = i; j >= 0; j--)
cout << bin[j];
}
int main()
{
cout << "Please enter a integer:\n";
int n;
cin >> n;
cout << "(decimal) " << n << " = (binary) ";
writebinary1(n);
cout << endl << endl;
cout << "Now, please enter a integer:\n";
cin >> n;
cout << "(decimal) " << n << " = (binary) ";
writebinary2(n);
cout << endl;
return 0;
}