N
(Leet Code c++)String to Integer(atoi) 본문
8. String to Integer (atoi)
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 charcter 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 [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 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.
Example 4:
Input: s = "words and 987" Output: 0 Explanation: Step 1: "words and 987" (no characters read because there is no leading whitespace) ^ Step 2: "words and 987" (no characters read because there is neither a '-' nor '+') ^ Step 3: "words and 987" (reading stops immediately because there is a non-digit 'w') ^ The parsed integer is 0 because no digits were read. Since 0 is in the range [-231, 231 - 1], the final result is 0.
Example 5:
Input: s = "-91283472332" Output: -2147483648 Explanation: Step 1: "-91283472332" (no characters read because there is no leading whitespace) ^ Step 2: "-91283472332" ('-' is read, so the result should be negative) ^ Step 3: "-91283472332" ("91283472332" is read in) ^ The parsed integer is -91283472332. Since -91283472332 is less than the lower bound of the range [-231, 231 - 1], the final result is clamped to -231 = -2147483648.
Constraints:
- 0 <= s.length <= 200
- s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'.
문자열을 int형으로 바꾸는 구현문제.
주어진 조건을 차례대로 수행하면 된다.
처음 시작할 작업은 띄어쓰기를 skip하면 된다.
주어진 s를 한 문자씩 읽으면서 ' '이 아닐 때까지 index를 늘려준다.
이후 for문을 index ~ s.size()만큼 반복하여, 문자를 읽도록 하자.
우선 '-'와 '+'가 있는지 확인하자.
처음 시작할 때 sign = 1로 했으니 양수인 상태이다.
그러나 s에서 '-'나 '+'가 있으면 이를 알맞게 바꿔줘야 한다.
op 변수는 이전에 '-' 또는 '+'를 읽은 적이 있는지 확인하는 변수다.
num 변수는 answer 문자열에 숫자가 들어있는지 확인하는 변수다.
두 변수 모두 false인 상태여야 부호를 바꿀 수 있다.
만약 둘 중 하나라도 true라면 문자 읽는 것을 멈춰야 한다.
다음은 숫자를 읽어야 한다.
'0' ~ '9'에 해당하는 문자가 읽히면 num을 true로 바꿔준다.
이후 answer가 비어있는지 확인한다.
answer가 비어있지 않으면 현재 문자와 answer가 INT_MIN ~ INT_MAX 사이인지 확인해야 한다.
만약 answer + s[i]가 INT_MIN보다 작게 된다면 INT_MIN을 리턴,
INT_MAX보다 크게 된다면 INT_MAX를 리턴하면 된다.
그렇지 않다면 answer에 그대로 현재 숫자를 이어 붙여주도록 한다.
이 외의 조건이 나오게 된다면 문자 읽는 것을 멈추도록 한다.
그리고 answer가 비어있는지 확인하여 알맞게 리턴을 해주면 된다.
class Solution {
public:
int myAtoi(string s) {
string answer = "";
int index = 0;
int length = s.size();
int sign = 1;
bool op = false;
bool num = false;
while(index < length && s[index] == ' '){
index++;
}
for(int i = index; i < length; i++){
if(s[i] == '-' || s[i] == '+'){
if(!op && !num){
op = true;
if(s[i] == '-'){
sign = -1;
}
}
else{
break;
}
}
else if(s[i] >= '0' && s[i] <= '9'){
num = true;
if(!answer.empty()){
int tmp = sign * stoi(answer);
if(tmp > INT_MAX / 10 || tmp == INT_MAX / 10 && (s[i] - '0') > 7){
return INT_MAX;
}
if(tmp < INT_MIN / 10 || tmp == INT_MIN / 10 && (s[i] - '0') > 7){
return INT_MIN;
}
}
answer += s[i];
}
else{
break;
}
}
if(!answer.empty()){
return sign * stoi(answer);
}
else{
return 0;
}
}
};
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)Factorial Trailing Zeroes (0) | 2021.07.21 |
---|---|
(Leet Code c++)Excel Sheet Column Number (0) | 2021.07.21 |
(Leet Code c++)Majority Element (0) | 2021.07.20 |
(Leet Code c++)Excel Sheet Column Title (0) | 2021.07.20 |
(Leet Code c++)Two Sum(2) - Input array is sorted (0) | 2021.07.20 |