To convert a string to an integer, we need to handle leading whitespaces, sign characters
('+'
or '-'), and numeric characters. We
iterate
through the
string,
skipping
leading spaces, and then
check
for a
sign
. After that, we
process
the numeric characters
to
build
the integer. If
the result exceeds the
32-bit signed integer range
,
we
clamp
it to INT_MIN
or
INT_MAX
. This ensures we
handle edge cases and invalid inputs gracefully.
class Solution { public int myAtoi(String s) { boolean isFirstCharacter = true; int sign = 1; long num =0; for(int i=0;i<s.length();i++){ char ch = s.charAt(i); if(ch==' '){ //"334234 3423"; if(!isFirstCharacter) break; } else if(ch=='+'){ if(!isFirstCharacter) break; else{ sign = 1; isFirstCharacter = false; } } else if(ch=='-'){ if(!isFirstCharacter) break; else{ sign = -1; isFirstCharacter = false; } } else if(Character.isDigit(ch)){ num = num*10 + ch-'0'; if(num*sign>Integer.MAX_VALUE) return Integer.MAX_VALUE; else if(num*sign < Integer.MIN_VALUE) return Integer.MIN_VALUE; isFirstCharacter = false; } else break; } return (int)num*sign; } }
The algorithm iterates through the string once, making it linear in time complexity.
The algorithm uses a constant amount of extra space, regardless of the input size.