[Leetcode] 8. String to Integer (atoi)
2024. 3. 12. 23:06ㆍTech: Algorithm
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).
The algorithm for myAtoi(string s) is as follows:
- Read in and ignore any leading whitespace.
- Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
- Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
- Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
- If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2^31 should be clamped to -2^31, and integers greater than 2^31 - 1 should be clamped to 2^31 - 1.
- Return the integer as the final result.
Note:
- Only the space character ' ' is considered a whitespace character.
- Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
Example 1:
Input: s = "42"
Output: 42
Explanation: The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^
The parsed integer is 42.
Since 42 is in the range [-231, 231 - 1], the final result is 42.
Example 2:
Input: s = " -42"
Output: -42
Explanation:
Step 1: " -42" (leading whitespace is read and ignored)
^
Step 2: " -42" ('-' is read, so the result should be negative)
^
Step 3: " -42" ("42" is read in)
^
The parsed integer is -42.
Since -42 is in the range [-231, 231 - 1], the final result is -42.
Example 3:
Input: s = "4193 with words"
Output: 4193
Explanation:
Step 1: "4193 with words" (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range [-231, 231 - 1], the final result is 4193.
Constraints:
- 0 <= s.length <= 200
- s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
Solution
문자열을 읽어서 숫자로 반환하는 함수를 만드는 것이 이번 문제..!
step1 ) whitespace를 넘기고
step2 ) + / - 일때는 index++, 부호 저장
step3) 문자가 나오거나 string s끝까지 읽을 때까지 문자를 저장하는데 이 때 문제 7번풀때처럼 INT_MAX/10을 나누는 방법을 활용했더니 처음으로 제대로 Accept..!
class Solution {
public:
int myAtoi(string s) {
int l = s.length();
int ret = 0;
int i=0;
bool negative = false;
// step 1
while(isspace(s[i]))
{
i++;
}
//step 2
if(s[i]=='-'){
negative = true;
i++;
}
else if(s[i]=='+'){
i++;
}
//step 3
while(isdigit(s[i]) && i<l)
{
int num = s[i]-'0';
if(ret>(INT_MAX-num)/10){
return negative? INT_MIN:INT_MAX;
}
// cout << ret << "+" << num << endl;
ret = ret*10+num;
i++;
}
return negative? ret*(-1): ret;
}
};
다른 사람들 푼걸 보니
isspace 대신 s[index] == ' '
isdigit 대신 return ch >= '0' && ch <= '9';
integer overflow를 피하는 방법으로는 if(result > (INT_MAX / 10) || (result == (INT_MAX / 10) && digit > 7)){
이렇게 쓴 것을 확인!
'Tech: Algorithm' 카테고리의 다른 글
[Leetcode] 10. Regular Expression Matching (0) | 2024.03.13 |
---|---|
[Leetcode] 9. Palindrome Number (0) | 2024.03.12 |
[Leetcode] 7. Reverse Integer (0) | 2024.03.11 |
[Leetcode] 6. Zigzag Conversion (0) | 2024.03.08 |
[Leetcode] 5. Longest Palindromic Substring (0) | 2024.03.07 |