[Leetcode] 8. String to Integer (atoi)
[Leetcode] 8. String to Integer (atoi)

[Leetcode] 8. String to Integer (atoi)

카테고리
📚 Algorithm
작성자
박용성박용성
작성일
2024년 08월 08일
태그
Python
Leetcode
Slug
Leetcode-8
floatFirstTOC: right

🖥️ 시작하며

문자를 숫자로 변환하는 함수를 작성하는 것이 목표다. 조건은 아래와 같다.
  • 공백은 무시한다.
  • 맨 앞 부호를 제외한 문자를 무시한다.
    • 맨 앞 문자가 부호가 아닌 문자라면 전체를 무시한다.
  • int 형의 범위를 넘는다면 해당 부분의 최댓값을 리턴한다.
 

⚙️ Python

1️⃣ 개선 전 버전

class Solution: def myAtoi(self, s: str) -> int: s = s.strip() # 공백 제거 sign = 1 # 부호 res = 0 # 결과값 if s == "" or s[0].isalpha(): # 문자열이 비어있거나 문자로 시작하는 경우 return 0 if s[0] == "+" or s[0] == "-": # 부호가 있는 경우 sign = -1 if s[0] == "-" else 1 s = s[1:] for i in s: if not i.isdigit(): break res = res * 10 + int(i) return min(res, 2**31 - 1) if sign == 1 else max(-res, -(2**31)) if __name__ == "__main__": sol = Solution() print(sol.myAtoi("-42"))
 

2️⃣ 개선 후 버전

class Solution: def myAtoi(self, s: str) -> int: s = s.strip() # 공백 제거 if not s: return 0 sign = 1 res = 0 int_max, int_min = 2**31 - 1, -(2**31) if s[0] in "+-": sign = -1 if s[0] == "-" else 1 s = s[1:] for char in s: if not char.isdigit(): break res = res * 10 + int(char) # 성능 향상을 위해 범위를 넘었을 경우 즉시 리턴 if sign == 1 and res > int_max: return int_max if sign == -1 and res * sign < int_min: return int_min return max(int_min, min(sign * res, int_max)) if __name__ == "__main__": sol = Solution() print(sol.myAtoi("-42"))

⚙️ C++

#include <cctype> // for std::isdigit #include <iostream> #include <limits> // for std::numeric_limits #include <string> class Solution { public: int myAtoi(const std::string &str) { int i = 0, sign = 1; long result = 0; // long을 사용하여 오버플로우 방지 // 1. 공백 스킵 while (i < str.size() && std::isspace(str[i])) { i++; } // 2. 부호 존재하면 처리 if (i < str.size() && (str[i] == '+' || str[i] == '-')) { sign = (str[i] == '-') ? -1 : 1; i++; } // 3. 숫자로 변환 while (i < str.size() && std::isdigit(str[i])) { int digit = str[i] - '0'; // 4. 오버플로우, 언더플로우 처리 if (result > (std::numeric_limits<int>::max() - digit) / 10) { return (sign == 1) ? std::numeric_limits<int>::max() : std::numeric_limits<int>::min(); } result = result * 10 + digit; i++; } return static_cast<int>(result * sign); } }; int main() { Solution sol; std::cout << sol.myAtoi("-42") << std::endl; // -42 return 0; }
 

📌 소감

댓글

guest