본문 바로가기
This is my cute cat.

Jaehee

Hi!

Thumbnail of LeetCode - 8. String to Integer (atoi)

LeetCode - 8. String to Integer (atoi)

시리즈: LeetCode

작성일 수정일

목차

문제 개요

난이도 - MEDIUM 사용 언어 - C++

문자열에서 정수형으로 parse하는 atoi 함수를 구현하는 문제입니다.

변환 시 적용되는 규칙은 아래와 같습니다.

  1. 공백 문자는 모두 무시한다.
  2. ‘-’, ‘+’ 문자가 처음 등장하고 이전에 등장한 적이 없다면, 해당 부호가 정수의 부호를 결정합니다. 만약 어떤 부호도 등장하지 않았다면 양수로 가정합니다.
  3. 숫자 문자가 아닌 문자가 등장하면 남은 모든 문자는 무시합니다.
  4. 숫자 문자는 정수형으로 변환합니다. 만약 숫자가 아니라면 정수 값은 0으로 결정됩니다.
  5. 만약 정수형 범위를 벗어난다면 정수형 범위의 최대/최소 값을 반환합니다.

문제 - LeetCode 8. String to Integer (atoi)

풀이

Solution

for (int index = 0; index < s.size() ; index++)
{
    char chr = s[index];
    
    ...
}

먼저 문자열을 순회합니다.

if ((chr < '0' || chr > '9') && !((result == 0) && (chr == '+' || chr == '-')))
{
    if (result == 0 && !(chr == '+' || chr == '-' || chr == ' ')) break;
    if (chr == '.') break;

    if (findSign) break;
    else continue;
}

순회 중 숫자 문자가 아니거나, 이미 부호가 결정된 상태에서 -, + 문자가 탐색되는 경우를 처리합니다.

if (chr == '+') 
{
    if (findSign) break;
    neg = false;
    findSign = true;
}
else if (chr == '-') 
{
    if (findSign) break;
    neg = true;
    findSign = true;
}
else 
{
    int num = (neg ? -(chr - '0') : (chr - '0'));
    if (result > INT_MAX/10 || (result == INT_MAX / 10 && num > 7)) return INT_MAX;
    if (result < INT_MIN/10 || (result == INT_MIN / 10 && num < -8)) return INT_MIN;

    findSign = true;
    result *= 10;
    result = result + num;
}

부호 문자라면 부호를 결정하고, 숫자라면 수를 계산하여 result 변수에 저장합니다.

제출 결과

Solution 1 result

실행 결과 0ms가 나왔습니다.

코드 전문
#include <string>
#include <climits>

class Solution 
{
public:
    int myAtoi(std::string s) 
    {
        if (!s.size()) return 0;

        int result = 0;
        bool neg = false;
        bool findSign = false;

        for (int i = s.size() - 1; i >= 0 ; i--)
        {
            int index = s.size() - i - 1;
            char chr = s[index];

            if ((chr < '0' || chr > '9') && !((result == 0) && (chr == '+' || chr == '-')))
            {
                if (result == 0 && !(chr == '+' || chr == '-' || chr == ' ')) break;
                if (chr == '.') break;

                if (findSign) break;
                else continue;
            }

            if (chr == '+') 
            {
                if (findSign) break;
                neg = false;
                findSign = true;
            }
            else if (chr == '-') 
            {
                if (findSign) break;
                neg = true;
                findSign = true;
            }
            else 
            {
                int num = (neg ? -(chr - '0') : (chr - '0'));
                if (result > INT_MAX/10 || (result == INT_MAX / 10 && num > 7)) return INT_MAX;
                if (result < INT_MIN/10 || (result == INT_MIN / 10 && num < -8)) return INT_MIN;

                findSign = true;
                result *= 10;
                result = result + num;
            }
        }

        return result;
    }
};

LeetCode 시리즈의 다른 게시물 보기

Thumbnail of LeetCode - 12. Integer to Roman

정수형 숫자가 주어질 때 로마 숫자로 변환합니다.

Thumbnail of LeetCode - 11. Container With Most Water

다양한 길이를 가진 막대들을 이용해 가장 많은 액체를 담을 수 있는 양을 구합니다.

Thumbnail of LeetCode - 10. Regular Expression Matching

정규 표현식 "."과 "*"을 구현하여 문자열에서 패턴을 탐색합니다.

Thumbnail of LeetCode - 9. Palindrome Number

입력된 정수가 회문인지 검사합니다.

Thumbnail of LeetCode - 8. String to Integer (atoi)

입력된 문자열에서 정수를 Parsing하는 atoi 함수를 구현합니다.

Thumbnail of LeetCode - 7. Reverse Integer

주어진 정수를 뒤집어(Reverse) 변환합니다.

Thumbnail of LeetCode - 6. Zigzag Conversion

문자열을 지그재그로 변환합니다.

Thumbnail of LeetCode - 5. Longest Palindromic Substring

주어진 문자열 중 가장 긴 회문(Palindrome)을 구합니다.