点击查看代码
//Convert a number from decimal to binary
#include<iostream>
using namespace std;
struct node {
int data;
node* next;
};
node* A;
void insert(int x) {
node* temp = new node;
temp->data = x;
temp->next = NULL;
if (A == NULL) {
A = temp;
return;
}
node* run = A;
while (run->next != NULL) {
run = run->next;
}
run->next = temp;
}
void reverse(node* prev) {
if (prev->next == NULL) {
A = prev;
return;
}
reverse(prev->next);
node* back = prev->next;
back->next = prev;
prev->next = NULL;
}
void print() {
node* run = A;
while (run != NULL) {
cout << run->data << " ";
run = run->next;
} cout << endl;
}
void FindDigiteInDecimal(int n) {
A = NULL;
int rem;//余数
while (n > 0) {
rem = n % 10;//每个位数上的数字,倒序
insert(rem);
n = n / 10;//商
}
reverse(A);//反转
print();
}
void FindDigiteInBinary(int n) {
A = NULL;
int rem;
while (n > 0) {
rem = n % 2;
insert(rem);
n = n / 2;
}
reverse(A);
print();
}
int main() {
int n;
cin >> n;
FindDigiteInDecimal(n);
FindDigiteInBinary(n);
}