一、Myitoa
1.初级版
void Myitoa( char str[100],int num)
{
assert(str != NULL);
int i = 0;
int a = 0;
int b = 0;
int tmp0 = 0;
char tmp[100];
if(num <0){
num = -num;
tmp0 = -1;
}
while (num>0)
{
tmp[i] = (num % 10)+'0';
num = num / 10;
i++;
}
b = i-1;//数组长度
if(tmp0<0){
tmp[i] = '-';
i++;
}
tmp[i] = '\0';
int j = 0;
i--;
/* do //ok
{
str[j] = tmp[i];
j++;
i--;
}
while(i>=0);*/
while(i>=0)
{
str[j] = tmp[i];
j++;
i--;
}
i = 0;
/*if(num == 0)
{
str[j] = '0';
}
str[j] = '\0';
}*/
int main()
{
char s[10] = {};
char s1[10] = {};
char s2[10] = {};
char s3[10] = {};
Myitoa(s,1234);
printf("%s\n", s);
Myitoa(s1,-1234);
printf("%s\n", s1);
Myitoa(s2,9);
printf("%s\n", s2);
Myitoa(s3,0);
printf("%s\n", s3);
return 0;
}
2.升级版(支持2~36进制)
{
char *str = (char *)malloc(sizeof(char)*(len));
char *str0 = (char *)malloc(sizeof(char)*(len+1));
//char *str2 = str0;
int i = 0;
int m = 0;
int j = 0;
int tmp = 0;
if(radix>=2 && radix<= 10)
{
while(num>0)
{
tmp = num%radix;
str[m] = tmp + '0';
num/=radix;
m++;
}
}
if(radix>10 && radix<=36)
{
m = 0;
while(num>0)
{
tmp = num%radix;
if(tmp >=0 && tmp <=9)
{
str[m] = tmp + '0';
}
if(tmp >9)
{
str[m] = tmp-10 + 'a';
}
num/=radix;
m++;
}
}
{
str0[j] = str[m-1];
j++;
m--;
}
str0[j] = '\0';
return str0;
free(str);
free(str0);
}
{
printf("%s\n",Myitoa(123,3,16));
printf("%s\n",Myitoa(12311,5,2));
printf("%s\n",Myitoa(12334,5,6));
printf("%s\n",Myitoa(123665,6,36));
return 0;
}
#include<stdio.h>
#include<assert.h>
#include<ctype.h>
int Myatoi(const char *str)
{
assert(str != NULL);
int tmp = 0;
if(*str == '-'){
while(isdigit(*(str+1))){
tmp = tmp * 10+((*(str+1))-'0');//数字在ASCII表里是连续的,*str-'0':ASCII值相减结果是整型数字
str++;
}
return (-tmp);
}
else{
while(isdigit(*str)){
tmp = tmp * 10+(*str-'0');//数字在ASCII表里是连续的,*str-'0':ASCII值相减结果是整型数字
str++;
}
return tmp;
}
return 0;
}
* Myatoi测试用例 */
int main()
{
/*char arr[10] = "a42";
char brr[10] = "1a42";
char crr[10] = "-2";
char drr[10] = "-24";
char err[10] = "142";*/
char frr[100] = "1234567898765";
/*printf("%d\n",Myatoi(arr));
printf("%d\n",Myatoi(brr));
printf("%d\n",Myatoi(crr));
printf("%d\n",Myatoi(drr));
printf("%d\n",Myatoi(err));*/
printf("%u\n",Myatoi(frr));
return 0;
}
{
union A
{
int a;
char b;
}c;
c.a = 1;
if(c.b == 1)
return true;
else
return false;
}
{
printf("%d\n",Islittle());
return 0;
}