Skip to content

Commit 7bca58f

Browse files
add problem 8 add test function
1 parent 8b9d497 commit 7bca58f

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

C/1-50/8-String-to-Integer-atoi.c

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
* Implement atoi to convert a string to an integer.
3+
*
4+
* Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
5+
*
6+
* Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
7+
* Created by supercoderhawk on 2017/7/23.
8+
*/
9+
#include
10+
#include
11+
12+
int myAtoi(char* str) {
13+
char* tmp = str;
14+
int length = 0, negative = 0,digit = 0;
15+
long long result = 0, preResult = 0;
16+
while (*tmp != '\0')
17+
{
18+
length ++;
19+
tmp++;
20+
}
21+
22+
// 处理开头空格
23+
while(str[0] == ' ')
24+
{
25+
str ++;
26+
length -- ;
27+
}
28+
if (length == 0)
29+
return 0;
30+
31+
// 处理正负
32+
if(str[0] == '-')
33+
negative = 1;
34+
if(str[0] == '-' || str[0] == '+')
35+
{
36+
str ++;
37+
length --;
38+
}
39+
40+
for(int i = 0; i < length; i++)
41+
{
42+
digit = (int)str[i];
43+
if( digit>= 0x30 && digit <= 0x39){
44+
preResult = result;
45+
result = result*10+digit-0x30;
46+
if(result<0 || preResult > result)
47+
if(negative)
48+
return INT_MIN;
49+
else
50+
return INT_MAX;
51+
}
52+
else{
53+
if(negative)
54+
result*= -1;
55+
if(result > INT_MAX )
56+
return INT_MAX;
57+
if (result < INT_MIN)
58+
return INT_MIN;
59+
return (int)result;
60+
}
61+
}
62+
if(negative)
63+
result*= -1;
64+
if(result > INT_MAX )
65+
return INT_MAX;
66+
if (result < INT_MIN)
67+
return INT_MIN;
68+
return (int)result;
69+
}
70+
71+
void testMyAtoi()
72+
{
73+
// printf("%d\n",myAtoi(" -0012a12"));
74+
// printf("%d\n",myAtoi("9223372036854775809"));
75+
printf("%d\n",myAtoi("18446744073709551617"));
76+
printf("%d\n",myAtoi("1"));
77+
}

0 commit comments

Comments
 (0)