#include <stdio.h>>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stack>
//char*是转换后存储的字符组
//n是需要被转换的整型数字
//radix是输入想要转入的多少进制
//在转换中,需要先除后模,再取余,但是需要逆置
//需要把每一个取出来的余数存储到字符数组里
char *Myitoa(char *str, int n, int radix)
{
const char array[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *ptr = str;
bool negative = false;
if(n == 0)
{
*ptr++ = 0;
*ptr = '\0';
return NULL;
}
if(n < 0)
{
n *= -1;
*ptr++ = '-';
negative = true;
}
while(n)
{
*ptr++ = array[n%radix];
n /= radix;
}
*ptr = '\0';
ptr--; //重新让ptr指向字符串内容
//此时str仍然指向的是字符串开始的位置
char *start = (negative)?str+1:str;
//对所转换的字符串内容进行逆置
while(start < ptr)
{
char tmp = *ptr;
*ptr = *start;
*start = tmp;
ptr--;
start++;
}
return NULL;
}
int main()
{
char str[30] = {0};
Myitoa(str,12,10);
printf("%s\n",str);
char str1[30] = {0};
Myitoa(str1,-3,10);
printf("%s\n",str1);
char str2[30] = {0};
Myitoa(str2,0,8);
printf("%s\n",str2);
char str3[30] = {0};
Myitoa(str3,-16,16);
printf("%s\n",str3);
return 0;
}