File tree Expand file tree Collapse file tree 1 file changed +7
-26
lines changed Expand file tree Collapse file tree 1 file changed +7
-26
lines changed Original file line number Diff line number Diff line change @@ -39,44 +39,25 @@ public int myAtoi( String str )
39
39
}
40
40
41
41
// 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 ;
57
44
58
45
// apply sign
59
46
int sign = 1 ;
60
- if ( str .charAt ( beginPos ) == '-' )
47
+ if ( str .charAt ( index ) == '-' )
61
48
{
62
- beginPos ++;
49
+ index ++;
63
50
sign = -1 ;
64
51
}
65
- else if ( str .charAt ( beginPos ) == '+' )
52
+ else if ( str .charAt ( index ) == '+' )
66
53
{
67
- beginPos ++;
54
+ index ++;
68
55
sign = 1 ;
69
56
}
70
-
71
- // handle illegal input
72
- if ( beginPos >= str .length () )
73
- {
74
- return 0 ;
75
- }
76
57
77
58
// calculate result
78
59
long result = 0 ;
79
- for ( int i = beginPos ; i <= endPos ; i ++ )
60
+ for ( int i = index ; i < str . length () ; i ++ )
80
61
{
81
62
if ( str .charAt ( i ) < '0' || str .charAt ( i ) > '9' )
82
63
{
You can’t perform that action at this time.
0 commit comments