题目描述:输入十进制数字串
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
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; isrcLen; i++)
{
srcNum *= 10;
srcNum += Source[i] - '0';
}
int remainder = 0, i = 0;
while(srcNum0 i=32)
{
remainder = srcNum % n;
Destination[i++] = scale[remainder];
srcNum /= n;
}
Destination[i--] = '\0';
for(int j = 0; j i; j++, i--)
{
int t = Destination[i];
Destination[i] = Destination[j];
Destination[j] = t;
}
return Destination;
}
int main()
{
const char *str_from = "3275432";
int n = 26;
char *str_to = NULL;
str_to = base_convert(str_from, n);
printf("%s",str_to);
if(str_to != NULL)
{
free(str_to);
str_to = NULL;
}
return 0;
}