Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit8091a52

Browse files
author
ssjssh
committed
完成leecode第8题。
1 parent88a78d8 commit8091a52

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+
staticintintToString(inti,char*arr){
7+
intt_len=sprintf(arr,"%d",i);
8+
arr[t_len]='\0';
9+
returnt_len;
10+
}
11+
staticintmyStrcmp(char*start,char*end,char*other){
12+
for(char*c1=start,*c2=other;c1<=end&&c2!='\0';c1++,c2++){
13+
if (*c1>*c2){
14+
return1;
15+
}elseif(*c1<*c2){
16+
return-1;
17+
}
18+
}
19+
return0;
20+
}
21+
22+
intmyAtoi(char*str) {
23+
intis_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+
}elseif((*c=='-'|| (*c >='0'&&*c<='9')||*c=='+')&&start==NULL){
29+
start=c;
30+
if(*c=='-'){
31+
is_negative=1;
32+
}
33+
}elseif(*c >='0'&&*c<='9'&&start!=NULL){
34+
end=c;
35+
}else{
36+
break;
37+
}
38+
}
39+
40+
if(start==NULL){
41+
return0;
42+
}elseif (end==NULL){
43+
end=start;
44+
}
45+
46+
if(*start=='+'){
47+
start++;
48+
}
49+
50+
// printf("%c:%c\n",*start,*end);
51+
//检查是否越界
52+
intresult_len=end-start+1;
53+
if(is_negative){
54+
charmin_str[40];
55+
intmin_len=intToString(INT_MIN,min_str);
56+
if(result_len>min_len|| (result_len==min_len&&myStrcmp(start,end,min_str)>0)){
57+
returnINT_MIN;
58+
}
59+
}else{
60+
charmax_str[40];
61+
intmax_len=intToString(INT_MAX,max_str);
62+
if(result_len>max_len|| (result_len==max_len&&myStrcmp(start,end,max_str)>0)){
63+
returnINT_MAX;
64+
}
65+
}
66+
67+
intresult=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+
returnresult;
81+
}
82+
83+
84+
intmain(){
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+
return0;
98+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp