題目:已知十進制和二十六進制的串,將他們相互轉化,輸出數字每三位一個分隔。
分析:數學,進制轉換。兩個方向的轉化是相同的,除了基數。
說明:注意輸出格式和數據長度。
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
char string[101];
char answer[101];
int number[101];
int main()
{
while (~scanf("%s",string)) {
if (strcmp(string, "*")) {
int base_from, base_to, length = strlen(string);
if (string[0] >= '0' && string[0] <= '9') {
base_from = 10;
base_to = 26;
for (int i = 0; i < length; ++ i) {
number[i] = string[length-1-i]-'0';
}
}else {
base_from = 26;
base_to = 10;
for (int i = 0; i < length; ++ i) {
number[i] = string[length-1-i]-'a'+1;
}
}
int loop = length*2;
for (int i = 0; i < loop; ++ i) {
int left = 0;
for (int j = length; j >= 0; -- j) {
left = left*base_from + number[j];
number[j] = left/base_to;
left = left%base_to;
}
answer[i] = left;
for (int j = 0; j < loop; ++ j) {
if (number[j] >= base_from) {
number[j+1] = number[j+1] + number[j]/base_from;
number[j] = number[j]%base_from;
}
}
}
int save = loop-1;
while (!answer[save]) {
save --;
}
if (base_to == 10) {
printf("%-22s",string);
}
for (int i = save; i >= 0; -- i) {
if (base_to == 26) {
printf("%c",answer[i]+'a'-1);
}else {
printf("%c",answer[i]+'0');
if (i > 0 && i%3 == 0) {
printf(",");
}
}
}
if (base_to == 26) {
for (int j = save; j < 21; ++ j) {
printf(" ");
}
for (int j = 0; j < length; ++ j) {
printf("%c",string[j]);
if (length-1 > j && (length-j)%3 == 1) {
printf(",");
}
}
}
puts("");
}
}
return 0;
}