-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmy_atoi.c
More file actions
65 lines (44 loc) · 893 Bytes
/
Copy pathmy_atoi.c
File metadata and controls
65 lines (44 loc) · 893 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int my_atoi(const char* s);
int main()
{
/*
const char* s = "123456";
long i;
i = (long)(s);
printf("%ld\n", i);
*/
char s[100];
while(1)
{
printf("\n:> ");
fgets(s, sizeof(s), stdin);
if(s[strlen(s) - 1] == '\n')
s[strlen(s) - 1] = '\0';
printf("%d %d\n", atoi(s), my_atoi(s));
}
return 0;
}
int my_atoi(const char* s)
{
// 123
//(s[0] - '0') * 100 + (s[1] - '0') * 10 + (s[2] - '0') * 1 ---> 123
int i = 0, r = 0, sign = 1;
// 跳过前导空白字符(' ', '\t', '\n')
while(s[i] == ' ' || s[i] == '\t' || s[i] == '\n')
i++;
// 判断符号
if(s[i] == '+') i++;
else if(s[i] == '-') sign = -1, i++;
while(s[i] != '\0')
{
// 碰到第一个非数字字符就停止转换
if(s[i] < '0' || s[i] > '9')
break;
r = r * 10 + s[i] - '0';
i++;
}
return r * sign;
}