十进制数与N进制数据的转换
问题描述:将从键盘输入的十进制数转换为N(如二进制、八进制、十六进制)进制数据。
#include<iostream>
using namespace std;
class List {
char data;
List* next;
List* head;
public:
List();
~List();
void push(int x);
void Print();
};
int main() {
int x;
cin >> x;
if (x > 0) {
List l;
l.push(x);
l.Print();
}
}
List::List()
{
this->next = NULL;
this->head = NULL;
}
List::~List()
{
this->next = NULL;
this->head = NULL;
}
void List::push(int x)
{
int N;
cin >> N;//转为几进制
if (N >= 2 && N <= 36) {
char a[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//用字符串数组下标余要转的几进制对应
int y = 1;
while (x != 0) {//求余
char b;
y = x % N;
x = x / N;
b = a[y];//用新的一个字符存起来
List* p = new List;//头插法
p->data = b;
p->next = this->next;
this->next = p;
}
}
}
void List::Print()
{
while (this->next) {
List* p = this->next;
List* q = p;
cout << q->data;
this->next = p->next;
delete(q);
}
}