문제
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
풀이
우선 글의 앞에 공백이 있을 수도 있으니, 앞에 있는 공백을 전부 제거한다.
그 후 가장 첫 글자가 부호인 경우에 $sgn$변수에 부호를 저장해준다.
그리고 정답을 저장하는 변수인 $ans$에 $ans=ans*10 + str[i]-\text{'0'}$를 계속 더해주면 된다.
Reverse Integer 문제와 마찬가지로 boundary case처리를 해주면 끝난다.
Time Complexity : $O(n)$
코드
class Solution {
public:
int myAtoi(string str) {
int st, ans=0, sgn=1;
for(st=0;str[st]==' '&&st<str.length();st++);
if(str[st]=='-')
{
sgn=-1;
st++;
}
else if(str[st]=='+') st++;
for(int i=st;i<str.length();i++)
{
if(str[i]<'0' || str[i]>'9') break;
int num = str[i]-'0';
if(ans>INT_MAX/10 || (ans==INT_MAX/10 && num>7)) return INT_MAX;
if(ans<INT_MIN/10 || (ans==INT_MIN/10 && num>8)) return INT_MIN;
ans = ans * 10 + num*sgn;
}
return ans;
}
};
'PS > leetcode' 카테고리의 다른 글
[leetcode] 10. Regular Expression Matching (0) | 2019.04.28 |
---|---|
[leetcode] 9. Palindrome Number (0) | 2019.04.28 |
[leetcode] 7. Reverse Integer (0) | 2019.04.28 |
[leetcode] 6. ZigZag Conversion (0) | 2019.04.28 |
[leetcode] 5. Longest Palindromic Substring (0) | 2019.04.28 |