面试题的常客:
1 #include<stdio.h>
2 #include<stdint.h>
3 #include<malloc.h>
4 uint64_t char_to_num(char *str);
5 char * num_to_char(uint64_t num);
6 int main(void)
7 {
8 char *str = "123456";
9 uint64_t num = 123456;
10 char *s;
11 printf("%lld\n",char_to_num(str));
12 printf("%s\n",s=num_to_char(num));
13 free(s);
14 return 0;
15 }
16 /*字符串转数字*/
17 uint64_t char_to_num(char *str)
18 {
19 char *s = str;
20 short count = 0;
21 uint64_t lastnum = 0;
22 while (*s != '\0')
23 {
24 s++;
25 count++;//记录字符长度
26 }
27 for (int i = 0; i < count; i++)//循环相乘相加
28 {
29 lastnum *= 10;
30 lastnum +=str[i]-'0';//注意要减去字符0
31 }
32 return lastnum;
33 }
34 ///*数字转字符串数组,不好的地方在于需要指定数组大小*/
35 //char* num_to_char(uint64_t num)
36 //{
37 // static char str[32] = { 0 };
38 // int count = 0;
39 // uint64_t inum = num;
40 // while (inum)
41 // {
42 // count++;
43 // inum /= 10;//求出位数
44 // }
45 // for (int i=count-1; num != 0; num /= 10, i--)//求余之后放在数组对应位置
46 // { //所以之前的求位数很有必要
47 // str[i] = num % 10+'0';
48 // }
49 // return str;
50 //}
51 /*数字转字符串数组,动态分配需要的大小*/
52 char* num_to_char(uint64_t num)
53 {
54 char *str = malloc(sizeof(num));
55 int count = 0;
56 uint64_t inum = num;
57 while (inum)
58 {
59 count++;
60 inum /= 10;//求出位数
61 }
62 for (int i = count - 1; num != 0; num /= 10, i--)//求余之后放在数组对应位置
63 { //所以之前的求位数很有必要
64 str[i] = num % 10 + '0';
65 }
66 str[count] = '\0';//最后加上\0是为了输出的时候能正常终止
67 return str;
68 }
NOTE:
动态分配了内存,要记得释放,还要,这个代码虽然完成了要求,但是鲁棒性还不够,因为我没有判断给出的数据是否合理分布在数字0-9.或者字符0-9,实际开发中需要做个限定。