Post

leetcode(리트코드)8-String to Integer (atoi)

leetcode 8 - String to Integer 문제입니다.

1. 문제

https://leetcode.com/problems/string-to-integer-atoi/


2. Input , Output

Constraints:

  • 0 <= s.length <= 200
  • s consists of English letters (lower-case and upper-case), digits (0-9), ‘ ‘, ‘+’, ‘-‘, and ‘.’.

3. 분류 및 난이도

Medium 난이도 문제입니다.
leetcode Top 100 Interviewd 문제입니다.


4. 문제 해석

  • stoi()를 해주는 문제이지만.. 예외처리할 게 많습니다.

5. code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
    int myAtoi(string s) {
        if(s[0]>96 && s[0]<123 || s[0]=='.')
            return 0;
        //맨 처음이 공백인 경우 공백이 아닐때까지 점프합니다.
        if(s[0]==' ')
        {
            int i = 0;
            while(i<s.size() && s[0]==' ')
            {
                s = s.substr(1);
            }
        }
        int result;
        try
        {
            result = std::stoi(s);
        }
        //문자가 들어온 경우
        catch(invalid_argument& e)
        {
            return 0;
        }
        //오버플로우, 언더플로우인 경우
        catch(std::out_of_range& e)
        {
            if(s[0]=='-')
                result = -2147483648;
            else
                result = 2147483647;
        }
        return result;
    }
};

6. 결과 및 후기, 개선점

This post is licensed under CC BY 4.0 by the author.