Skip to content

Commit 8091a52

Browse files
author
ssjssh
committed
完成leecode第8题。
1 parent 88a78d8 commit 8091a52

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

src/ssj/leecode/atoi.c

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#include <stdio.h>
2+
#include <string.h>
3+
#include <limits.h>
4+
5+
6+
static int intToString(int i,char *arr){
7+
int t_len = sprintf(arr,"%d",i);
8+
arr[t_len] = '\0';
9+
return t_len;
10+
}
11+
static int myStrcmp(char *start,char *end,char *other){
12+
for(char *c1 = start,*c2 = other;c1<=end&&c2!='\0';c1++,c2++){
13+
if (*c1 > *c2){
14+
return 1;
15+
}else if(*c1 < *c2){
16+
return -1;
17+
}
18+
}
19+
return 0;
20+
}
21+
22+
int myAtoi(char* str) {
23+
int is_negative = 0;
24+
char *start=NULL,*end=NULL;
25+
for(char *c=str;c!='\0';c++){
26+
if(start==NULL && (*c == ' ' || *c =='\n' || *c == '\t')){
27+
continue;
28+
}else if((*c=='-' || (*c >='0' && *c<='9') || *c=='+') && start==NULL){
29+
start = c;
30+
if(*c == '-'){
31+
is_negative=1;
32+
}
33+
}else if(*c >='0' && *c<='9'&& start!=NULL){
34+
end = c;
35+
}else{
36+
break;
37+
}
38+
}
39+
40+
if(start==NULL){
41+
return 0;
42+
}else if (end==NULL){
43+
end = start;
44+
}
45+
46+
if(*start == '+'){
47+
start++;
48+
}
49+
50+
// printf("%c:%c\n",*start,*end);
51+
//检查是否越界
52+
int result_len = end - start + 1;
53+
if(is_negative){
54+
char min_str[40];
55+
int min_len = intToString(INT_MIN,min_str);
56+
if(result_len>min_len || (result_len == min_len && myStrcmp(start,end,min_str)>0)){
57+
return INT_MIN;
58+
}
59+
}else{
60+
char max_str[40];
61+
int max_len = intToString(INT_MAX,max_str);
62+
if(result_len>max_len || (result_len == max_len && myStrcmp(start,end,max_str)>0)){
63+
return INT_MAX;
64+
}
65+
}
66+
67+
int result = 0;
68+
69+
// printf("%c:%c",*start,*end);
70+
for(char *c=start;c<=end;c++){
71+
if(*c != '-' && *c != '+'){
72+
result *= 10;
73+
result += (*c - '0');
74+
}
75+
}
76+
77+
if(*start=='-'){
78+
result = -result;
79+
}
80+
return result;
81+
}
82+
83+
84+
int main(){
85+
printf("%d\n",myAtoi("+1231312"));
86+
printf("%d\n",myAtoi(" -11919730356x"));
87+
printf("%d\n",myAtoi(" +1146905820n1"));
88+
printf("%d\n",myAtoi("1"));
89+
printf("%d\n",myAtoi("123"));
90+
printf("%d\n",myAtoi("-1231312"));
91+
printf("%d\n",myAtoi("-1231312fqwef"));
92+
printf("%d\n",myAtoi("-1231312 992"));
93+
printf("%d\n",myAtoi("3000000001"));
94+
printf("%d\n",myAtoi("-3000000001"));
95+
printf("%d\n",myAtoi("wefwqef-3000000001"));
96+
printf("%d\n",myAtoi(" -3000000001"));
97+
return 0;
98+
}

0 commit comments

Comments
 (0)