Skip to content

Commit b46f8d0

Browse files
author
freemanzhang
committed
refactor code
1 parent d78a093 commit b46f8d0

File tree

1 file changed

+7
-26
lines changed

1 file changed

+7
-26
lines changed

src/typeconversion/StringToInteger.java

Lines changed: 7 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -39,44 +39,25 @@ public int myAtoi( String str )
3939
}
4040

4141
// trim beginning and trailing spaces
42-
int beginPos = 0;
43-
while ( beginPos < str.length() && str.charAt( beginPos ) == ' ' )
44-
{
45-
beginPos++;
46-
}
47-
int endPos = str.length() - 1;
48-
while ( endPos >= 0 && str.charAt( endPos ) == ' ' )
49-
{
50-
endPos--;
51-
}
52-
53-
if ( beginPos >= str.length() )
54-
{
55-
return 0;
56-
}
42+
str = str.trim();
43+
int index = 0;
5744

5845
// apply sign
5946
int sign = 1;
60-
if ( str.charAt( beginPos ) == '-' )
47+
if ( str.charAt( index ) == '-' )
6148
{
62-
beginPos++;
49+
index++;
6350
sign = -1;
6451
}
65-
else if ( str.charAt( beginPos ) == '+' )
52+
else if ( str.charAt( index ) == '+' )
6653
{
67-
beginPos++;
54+
index++;
6855
sign = 1;
6956
}
70-
71-
// handle illegal input
72-
if ( beginPos >= str.length() )
73-
{
74-
return 0;
75-
}
7657

7758
// calculate result
7859
long result = 0;
79-
for ( int i = beginPos; i <= endPos; i++ )
60+
for ( int i = index; i < str.length(); i++ )
8061
{
8162
if ( str.charAt( i ) < '0' || str.charAt( i ) > '9' )
8263
{

0 commit comments

Comments
 (0)