🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 题目1: 把字符串转化为整数 有整数字符串,` "13579"`, 和 `"246810"`. 请写一个函数把这两个字符串转化为整数 步骤: * 先判断正负 * 遍历字符串,转换字符为整数 ``` //atoi.cc #include <stdio.h> int my_atoi(char *str) { bool bmin = false; int result = 0; //先判断正负 if ((*str > '9' || *str < '0') && (*str == '+' || *str == '-')) { if (*str == '-') bmin = true; str++; } while (*str != '\0') { if (*str > '9' || *str < '0') break; //printf("befter str: %s\n", str); result = result * 10 + (*str++ - '0'); //printf("after str: %s\n", str); } if (*str != '\0') return 0; return bmin ? -result : result; } int main() { char a[] = "13579"; char b[] = "246810"; printf("a: %d\n", my_atoi(a)); printf("b: %d\n", my_atoi(b)); } ``` 编译&运行 ``` $ g++ -o atoi atoi.cc $ ./atoi a: 13579 b: 246810 ``` ## 基础知识补充 * `*str++`: 它的运算顺序是先返回`*str`的值,然后`str`再`++`。 * `(*str)++`: 它的运算顺序是先返回`*str`的值,然后 `*str`的值再++ * `*(str++)`: 它的运算顺序是先返回`*str`的值,然后`str`再`++`。和`*str++`的运算顺序是一样的。 * `++*str`: 先将 `*str`的值`++`,然后再返回 `*str`的值。 * `++(*str)`: 先将 `*str`的值`++`,然后再返回` *str`的值,所以它和`++*str`是一样的。 * `* (++str)`,先将`str`的值`++`,然后再返回 `* str`的值,和 `*++str`是等价的。 `*str++ - '0'`: 表达式的意思是`字符 - ’0‘ = 整数`,可以通过ASCII码来计算。举个例子: ``` //ascii.cc int main() { int a = 2; char c = '3'; char b = '0' + a; int d = a + (c -'0'); printf("int + char = %c, d: %d\n",b,d); } ``` 编译运行 ``` $ gcc -g -o ascii ascii.cc $ ./ascii int + char = 2, d: 5 ``` 可以看到 `char b = '0' + a;` * `'0'`的十进制`ascii`值是`48` * `48 + 2 = 50` * `b`的值是字符`'2'`, 十进制`ascii`值是`50` ,对应的值是字符`'2'`,打印出来的值正确; 再看` int d = a + (c -'0');` * `c`的值是字符`'3'`,对应的十进制`ascii`是`51` * `c- ‘0’ = 51 - 48 = 3` * `int d = a + (c -'0') = a + 3 = 2 + 3 = 5 `, 打印出来的值正确; 可以得出结论: * 整数 + ‘0’ =整数值字符, 举例: `2 + '0' = '2';` * 字符 - ‘0‘ = 字符值整数, 举例:` ‘2’ - '0' = 2;` ## 题目2:把整数转化为字符串 请把整数`123456`转化为字符串; 步骤: * 求出整数的最大位(个/十/百/千/万) * 遍历位数,将整数转化为字符 ``` // itoa.cc int my_itoa(long i, char* str) { int power = 0, j = 0; j = i; //求出整数的最大位 for (power = 1; j>10; j /= 10) power *= 10; //遍历位数,将整数转化为字符 for (; power>0; power /= 10) { *str++ = '0' + i / power; i %= power; } *str = '\0'; } int main() { char str[7]; my_itoa(123456, str); printf("str: %s\n", str); } ``` 编译&运行 ``` $ g++ -g -o itoa itoa.cc -std=c++11 $ ./itoa str: 123456 ```