概述
题目描述:输入十进制数字串src
(0~INT_MAX),和一个数字n
(代表进制2~36),将src
转化为n
进制数字串返回。
输入:"10",2
输出:"1010"
输入:"10",15
输出:"A"
输入:"3275432",20
输出:"1098BC"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*enum
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
A, B, C, D, E, F, G, H, I, J,
K, L, M, N, O, P, Q, R, S, T,
U, V, W, X, Y, Z
};*/
char *base_convert(const char *Source, int n)
{
if(Source == NULL || n < 2)
return NULL;
char *Destination = (char *) malloc(sizeof(char) * (32+1));
//将源字符串转换成数字
int srcLen = strlen(Source);
int srcNum = 0;
char scale[] =
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'
};
for(int i=0; i<srcLen; i++)
{
srcNum *= 10;
srcNum += Source[i] - '0';
/* if(srcNum > INT_MAX_SIZE || srcNum < INT_MIN_SIZE)
return NULL;*/
}
int remainder = 0, i = 0;
//按照短除法正取余数,并查找余数对应枚举类型,填入字符串
while(srcNum>0 && i<=32)
{
remainder = srcNum % n;
Destination[i++] = scale[remainder];
srcNum /= n;
}
Destination[i--] = '